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:
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.
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.
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.
The above is the detailed content of Why is my setTimeout() function executing immediately, despite setting a delay?. For more information, please follow other related articles on the PHP Chinese website!