[英]How to execute one function with different timeouts in node.js 4.2.3
我是JavaScript和node.js的新手,所以我的问题可能很愚蠢,但是我尝试了。
我读了很多有关超时,关闭等的信息,但是我陷入了困境。 我想做的很简单:我拥有对象数组,并希望在不同的超时后对其所有元素运行一个函数。 例如,第一个为3秒,第二个为5秒,依此类推。 我该如何实现?
我写了一些测试代码(为了简化一次超时,但是我仍然需要不同的超时-代替“ i”的是具有自己属性(包括超时)的对象):
"use strict";
function test(i) {
console.log('%d', i);
}
var i = 0;
for(i = 0; i < 5; ++i) {
setTimeout(test(i), 1000);
console.log('here');
}
输出:
D:\Projects\js_projects>node timeout.js
<< why there is no 1000 ms delay here?
0
here
1
here
2
here
3
here
4
here
在开始和第一个元素输出之间没有延迟(为什么?)。
我期望这样的输出:
here
here
here
here
here
<1000 ms delay here>
0
1
2
3
4
我该如何实现?
其原因是由于setTimeout(test(i), 1000)
。 您实际上是在调用该函数。 您需要做的就是传递对该函数的引用,例如:
setTimeout(test, 1000); // test function will be executed after 1000ms
有关setTimeout的更多信息。
如果要使用该循环调用多个函数,则应使用类似以下内容的方法:
setTimeout(test, 1000 + (i * 100)); // 1000ms + 100ms per each i
如果您有5个循环,则它们的调用方式为:1000、1100、1200、1300、1400。
如果要向该函数传递一些参数,请使用第三个参数:
setTimeout(test, 1000 + (i * 100), i);
i
将被传递给该函数,以便您可以实际使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.