Skip to content Skip to sidebar Skip to footer

Nesting Setintervals Loops

How should two setInterval loops be nested? On the outer loop (setInterval1), I wish to make a server request every 4 seconds, and then in the inner joop (setInterval2), I wish to

Solution 1:

Do not nest setIntervals (except if you clear them, maybe)

This is what happens when you do so:

setInterval1
     ├────> function1 ────> setInterval2
     │                           ├────> function2
     │                           ├────────> function2
     │                           ├────────────> function2
     │                           ⋮
     ├────────> function1 ────> setInterval2
     │                               ├────> function2
     │                               ├────────> function2
     │                               ├────────────> function2
     │                               ⋮
     ├────────────> function1 ────> setInterval2
     │                                   ├────> function2
     │                                   ├────────> function2
     │                                   ├────────────> function2
     │                                   ⋮
     ├────────────────>  …
     ⋮

I recommend setTimeout instead:

var counter1 = 0;
var counter2 = 0;
(functiontimeout1() {
  console.log('counter1', counter1);
  counter1++;
  var i = 0;
  (functiontimeout2() {
    console.log('counter2', counter2);
    counter2++;
    ++i;
    setTimeout(i < 4 ? timeout2 : timeout1, 1000);
  })();
})();

Even if you nest them, they are usually less problematic than setInterval. But use some conditional to make sure you only call setTimeout when necessary.

var counter1 = 0;
var counter2 = 0;
(functiontimeout1() {
  console.log('counter1', counter1);
  counter1++;
  var i = 0;
  (functiontimeout2() {
    console.log('counter2', counter2);
    counter2++;
    ++i;
    if(i < 4) setTimeout(timeout2, 1000);
  })();
  setTimeout(timeout1, 4000);
})();

Solution 2:

You're creating a new interval every 4 seconds. Don't nest setInterval. Maybe what you really want is setTimeout?

Post a Comment for "Nesting Setintervals Loops"