Unexpected Immediate Function Execution with setTimeout
In an attempt to schedule a function call at specific intervals, the user encounters an issue where the setTimeout function executes the function immediately, despite the specified timeout. The doRequest function should be called at 10-second intervals, but it's being called right away.
The cause of this immediate execution lies in the way the setTimeout function is being called. The following code snippet demonstrates the issue:
setTimeout(doRequest(url, proxys[proxy]), proxytimeout);
In this code, the doRequest function is passed as the first argument to setTimeout, but the function is being executed immediately rather than being scheduled.
Solutions:
To resolve this issue and ensure that doRequest is scheduled, there are three alternative ways to use setTimeout:
Pass the Function Name as a String:
setTimeout('doRequest(' + url + ',' + proxys[proxy] + ')', proxytimeout);
Use an Anonymous Function:
(function(u, p, t) { setTimeout(function() { doRequest(u, p); }, t); })(url, proxys[proxy], proxytimeout);
Pass the Function Name First, Then the Parameters:
setTimeout(doRequest, proxytimeout, url, proxys[proxy]);
The above is the detailed content of Why Does My setTimeout Function Execute Immediately?. For more information, please follow other related articles on the PHP Chinese website!