1

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);
   }
 };
1
  • That is because all the 5 setTimeout get trigger at the same time, but with a different delay. So because they wait 1 - 5 seconds, they happen one second after each other. Commented Jul 11, 2015 at 20:59

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

All of the answers were great, and I understand that the previous answers directly answered the question, but I appreciate this demonstration.
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.