Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate]

As you give the function to the setTimeout in that form, the function is executed instead of passed to the setTimeout. You have three alternatives to make it work:

Give first the function, then the timeout and the parameters as the last arguments:

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

Or just write a string that will be evaluated:

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

Third style is to pass an anonymous function that calls the function. Note that in this case, you have to do it in a closure to prevent the values from changing in the loop, so it gets a bit tricky:

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

The second format is a bit hacky, but works nevertheless if the arguments are scalar values (strings, ints etc). The third format is a bit unclear, so in this case the first option will obviously work best for you.

Leave a Comment