为什么我应该由 setTimeout 安排的函数调用会立即执行? [英] Why is my function call that should be scheduled by setTimeout executed immediately?
问题描述
这是我的问题.我有这个功能来测试代理服务器.
Here's my issue. I have this function to test proxy servers.
function crawl() {
var oldstatus = document.getElementById('status').innerHTML;
document.getElementById('status').innerHTML = oldstatus + "Crawler Started...<br />";
var url = document.getElementById('url').value;
var proxys = document.getElementById('proxys').value.replace(/
/g,',');
var proxys = proxys.split(",");
for (proxy in proxys) {
var proxytimeout = proxy*10000;
setTimeout(doRequest(url,proxys[proxy]), proxytimeout);
}
}
我希望在大约 10 秒的间隔内调用 'doRequest()' 函数,但即使使用 setTimeout() 函数也会立即调用.
I want the 'doRequest()' function to be called in roughly 10 second intervals but even with the setTimeout() the functions are called immediately.
欢迎提出任何想法,谢谢.
Any ideas are welcome, thanks.
PS:即使我为 'proxytimout' 设置了一个任意值,它也没有任何效果.
PS: Even if I put an arbitrary value for 'proxytimout' it has no effect.
推荐答案
当您以这种形式将函数提供给 setTimeout 时,该函数将被执行,而不是传递给 setTimeout.您可以通过三种方式使其发挥作用:
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.
这篇关于为什么我应该由 setTimeout 安排的函数调用会立即执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!