Lim SY
Lim SY

Reputation: 185

setTimeout loop inside setInterval

I have code similar to this:

var count = 0;

setInterval(function() {
  if(count===0){
    console.log(123);
    count++;
  } else if(count>0) {
    for(i=1;i<=2;i++){
        (function(ind) {
            setTimeout(function() {
              console.log(ind);
            }, 1000 * ind);
        })(i);
    }
    count=0;
  }
},1000)

The result is not what I expected, what I'd like to achieve for the console log is like:

123
1
2
123
1
2
...

and so on for each interval with 1000ms. Also I'd like to ask is there a better way to do this? The number of setTimeout loop(2 for the above case) can/might be different each time.

Upvotes: 1

Views: 544

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074218

something like this, first print 123 and wait for 1000ms, then 1 and wait for 1000ms, finally 2 and wait for 1000ms after that repeat the whole process infinitely

If you want it regularly at 1000ms intervals, with an inner countdown then reset, you can just use a single setInterval:

// Uses a 100ms rather than 1000ms counter, stopping after two seconds
var count = 0;
var inner = 0;
var handle = setInterval(function() {
  if (inner == 0) {
    // Start again
    console.log(123);
    count = 0;
    // The number of "inner" counts to do
    inner = 2;
  } else {
    // An "inner" count
    ++count;
    --inner;
    console.log(count);
  }
}, 100);

// Stop it after two seconds, just for demo purposes
setTimeout(function() {
  clearInterval(handle);
}, 2000);

Upvotes: 1

Related Questions