1

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.

4
  • "...and so on for each interval with 1000ms..." Your inner setTimeout will sometimes be longer than 1000ms. What then? Commented Aug 4, 2016 at 8:32
  • 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 Commented Aug 4, 2016 at 8:36
  • @T.J.Crowder yes, i get repeated 123 Commented Aug 4, 2016 at 8:39
  • 1
    @T.J.Crowder Sorry my bad, wasn't paying attention. Will remove my comments since they are not contributing to the solution. Commented Aug 4, 2016 at 8:52

1 Answer 1

1

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);

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

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.