Home > Article > Web Front-end > Why is my `setTimeout` function being executed immediately instead of after the delay?
In this scenario, where a function is intended to be executed with a delay using setTimeout but is instead executed immediately, the issue lies in how the function is passed to setTimeout.
To resolve this issue, there are three approaches to ensure it executes with the desired delay:
Pass Arguments Individually:
setTimeout(doRequest, proxytimeout, url, proxys[proxy]);
This form passes the function first, followed by the timeout and the function's arguments.
Use a Literal String:
setTimeout('doRequest('+url+','+proxys[proxy]+')', proxytimeout);
Here, a literal string is provided, which will be evaluated at execution time.
Anonymous Function Closure:
(function(u, p, t) { setTimeout(function() { doRequest(u, p); }, t); })(url, proxys[proxy], proxytimeout);
This approach involves an anonymous function that calls the intended function. The closure ensures that the values used in the function remain consistent throughout the loop.
By adopting any of these methods, you can effectively schedule the execution of the doRequest function with the specified delay.
The above is the detailed content of Why is my `setTimeout` function being executed immediately instead of after the delay?. For more information, please follow other related articles on the PHP Chinese website!