简体   繁体   English

JavaScript中的setTimeout函数不会在正确的时间间隔输出数字

[英]setTimeout function in JavaScript doesn't output number at correct time intervals

I'm not understanding why this function outputs 1-5 in successive order as intended, but at 1 second intervals rather than 1,2,3, etc. seconds. 我不明白为什么此功能按预期的连续顺序输出1-5,但间隔为1秒,而不是1,2,3等秒。 I'm unfamiliar with the setTimeout function and I understand that something is going on with the arguments to the function here that I'm not seeing. 我对setTimeout函数不熟悉,并且我了解该函数的参数正在发生某些事情,而我却没有看到。

var counter = function() {
   for (var i = 1; i <= 5; i++) {
     (function(x){
       setTimeout(function timer() {
           console.log(x);
       }, (x * 1000));
     })(i);
   }
 };

You can avoid the for loop by calling it recursively, just pass the start and stop index. 您可以通过递归调用for循环来避免for循环,只需传递start和stop索引即可。

var counter = function (x, y) {
    setTimeout(function timer() {
        console.log(x);
        if (x != y) counter((x + 1),y);
    }, (x * 1000));
};

counter(1, 5);

Fiddle demo 小提琴演示

Because you are immediately placing all your calls to setTimeout . 因为您将立即将所有调用都置于setTimeout So, during the same event, JS receives the instruction to call timer : after 1000ms, after 2000ms, after 3000ms, after 4000ms and after 5000ms. 因此,在同一事件中,JS接收到调用timer的指令:1000ms之后,2000ms之后,3000ms之后,4000ms之后和5000ms之后。 Which is exactly what it does, so timer is called every 1 second. 它正是这样做的,因此每1秒调用一次timer

If you wish to progressively increase the interval, your loop should be rewritten as a recursive loop, in which the next call to setTimeout is performed by timer . 如果希望逐步增加间隔,则应将循环重写为递归循环,其中对setTimeout的下一次调用由timer

As @putvande said you are setting all 5 timeouts at the same time with different intervals. 正如@putvande所说,您要同时设置所有5个超时时间,且间隔不同。

var counter = function(){
   for (var i=1; i<=5; i++) {
     console.log('setting timer for ' + i);
     (function(x){
         setTimeout( function timer(){
         console.log(x);
     }, (x*1000) );
     })(i);
   }
 };

counter();

An extra log statement show this. 一条额外的日志语句显示了这一点。 Your timers are firing at the right interval, 1st one at 1 second, 2nd one at 2 seconds, etc. 您的计时器以正确的间隔触发,第一个1秒1秒,第二个2秒秒,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM