首頁  >  文章  >  web前端  >  儘管設定了延遲,為什麼我的 setTimeout() 函數仍立即執行?

儘管設定了延遲,為什麼我的 setTimeout() 函數仍立即執行?

Barbara Streisand
Barbara Streisand原創
2024-11-14 18:33:01464瀏覽

Why is my setTimeout() function executing immediately, despite setting a delay?

Delayed Execution of Function Calls with setTimeout

In JavaScript, using setTimeout() to schedule the execution of a function at a later time is a common technique for asynchronous programming. However, there are instances where the function is executed immediately despite being scheduled with a delay. Understanding the intricacies of setTimeout() is crucial for effective asynchronous execution.

In the provided context, the crawl() function is intended to call the doRequest() function at approximate 10-second intervals. However, the function is being executed immediately.

The key to understanding this issue lies in the syntax of setTimeout(). When providing a function as a parameter, it's important to specify the function itself, followed by the delay, and then any arguments the function requires.

Possible Solutions:

  1. Function, Delay, and Arguments:

    Call setTimeout() in the following manner:

    setTimeout(doRequest, proxytimeout, url, proxys[proxy]);

    This ensures that doRequest() is passed as the function to be executed, along with the delay and necessary arguments.

  2. Function as String:

    Alternatively, you can pass doRequest() as a string that will be evaluated:

    setTimeout('doRequest('+url+','+proxys[proxy]+')', proxytimeout);

    This approach requires fewer parentheses and provides a more concise alternative.

  3. Anonymous Function with Closure:

    Enclose doRequest() in an anonymous function to prevent argument changes within the loop:

    (function(u, p, t) {
       setTimeout(function() { doRequest(u, p); }, t);
    })(url, proxys[proxy], proxytimeout);

    This technique ensures that the variables used within the closure remain consistent, even as the loop progresses. However, it is slightly more complex than the previous options.

Depending on your specific needs, any of these solutions will effectively schedule the execution of doRequest() with the intended delay. Understanding the nuances of setTimeout() is essential for successful asynchronous programming in JavaScript.

以上是儘管設定了延遲,為什麼我的 setTimeout() 函數仍立即執行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn