Why Isn't My Function Scheduled by setTimeout Executing Immediately?
Your code seeks to test proxy servers using the setTimeout function to call doRequest with 10-second intervals. Strangely, the functions are executing immediately instead of following the intended schedule.
Understanding the Issue
The problem lies in how you're passing the doRequest function to setTimeout. When you specify a function as the first argument, as in setTimeout(doRequest(url, proxys[proxy]), proxytimeout), the function is invoked immediately.
Solutions
To resolve the issue, you have three options:
Pass the arguments as separate parameters:
setTimeout(doRequest, proxytimeout, url, proxys[proxy]);
Use a string expression:
setTimeout('doRequest(' + url + ',' + proxys[proxy] + ')', proxytimeout);
Define an anonymous function within a closure:
(function(u, p, t) { setTimeout(function() { doRequest(u, p); }, t); })(url, proxys[proxy], proxytimeout);
The first option is preferred as it's clearer and more explicit. The second option is less desirable due to its "hacky" nature, while the third option can be complex to understand but prevents values from changing within the loop.
The above is the detailed content of Why Is My `setTimeout` Function Executing Immediately Instead of at a Scheduled Time?. For more information, please follow other related articles on the PHP Chinese website!