Node.js的setTimeout()行为

我想要一段代码重复100次,其间有1秒的延迟。 这是我的代码:

for(var i = 0; i < 100; i++){ setTimeout(function(){ //do stuff },1000); } 

虽然这似乎是正确的,但事实并非如此。 而不是跑100次,等待1秒钟,等待1秒钟,然后毫不拖延地跑100次“做东西”。

有人有这个想法吗?

你可以使用setInterval()来完成它。

它调用我们select的函数,只要clearTimeout被调用到存储它的可变timer

看下面的例子:(并且记住打开你的开发者控制台(在chrome右击 – > inspect element – > console)来查看console.log )。

 // Total count we have called doStuff() var count = 0; /** * Method for calling doStuff() 100 times * */ var timer = setInterval(function() { // If count increased by one is smaller than 100, keep running and return if(count++ < 100) { return doStuff(); } // mission complete, clear timeout clearTimeout(timer); }, 1000); // One second in milliseconds /** * Method for doing stuff * */ function doStuff() { console.log("doing stuff"); } 

这里也是: jsfiddle的例子

作为奖励:您的原始方法将无法工作,因为您基本上尽可能快地分配100个setTimeout调用。 所以,而不是他们运行一秒钟的差距。 它们的运行速度与for循环放置队列的速度一样快,从当前时间1000毫秒开始。

例如,以下代码显示使用您的方法时的时间戳:

 for(var i = 0; i < 100; i++){ setTimeout(function(){ // Current time in milliseconds console.log(new Date().getTime()); },1000); } 

它会输出类似(毫秒)的东西:

 1404911593267 (14 times called with this timestamp...) 1404911593268 (10 times called with this timestamp...) 1404911593269 (12 times called with this timestamp...) 1404911593270 (15 times called with this timestamp...) 1404911593271 (12 times called with this timestamp...) 

你可以看到: js小提琴的行为

你需要使用callback,node.js是asynchronous的:

 function call_1000times(callback) { var i = 0, function do_stuff() { //do stuff if (i < 1000) { i = i + 1; do_stuff(); } else { callback(list); } } do_stuff(); } 

或者,更清洁:

 setInterval(function () { //do stuff }, 1000); 

现在你明白了for循环在几毫秒内迭代,另一种方法是简单地根据计数调整setTimeout延迟。

 for(var i = 0; i < 100; i++){ setTimeout(function(){ //do stuff }, i * 1000); } 

对于许多用例,这可能被认为是不好的。 但是在特定的情况下,如果你知道你绝对要在y秒钟之后运行代码x次,这可能是有用的。

还值得注意的是有一些相信使用setInterval是不好的做法 。