简体   繁体   中英

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. 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.

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.

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 . So, during the same event, JS receives the instruction to call timer : after 1000ms, after 2000ms, after 3000ms, after 4000ms and after 5000ms. Which is exactly what it does, so timer is called every 1 second.

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 .

As @putvande said you are setting all 5 timeouts at the same time with different intervals.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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