Search code examples
javascriptfunctionsetintervaldelayclearinterval

How to make a setTimeout to call a setInterval to make it execute after some time?


I want my doSomething to be executed after some amount of time different than the interval of the setInterval, so I used setTimeout(doSomething, 5000); so I could call doSomething after say 5 seconds, but that doesn't seem to happen.

Regarding that I need to use clearInterval for the setInterval to stop executing in the condition I declared, and I need to have an interval time for the setInterval to be different from the delay of doSomething execution start, how can I make doSomething to start executing after 5 seconds?

function doSomething() {
  let a = 1;
  return setInterval(() => {
    console.log(a);
    if (a < 6) {
      a++;
    } else {
      return a = 1;
      clearInterval(id);
    }
  }, 1000);
}

var id = doSomething();
setTimeout(doSomething, 5000);


Solution

  • var id = doSomething(); calls the function (and thus starts the interval) immediately. Since both the setInterval() and clearInterval() are within the same function, there is no need to return the interval ID. Just keep track of it locally in the function. That way you only need to invoke doSomething() and it will start and stop by itself.

    Lastly, note that setInterval()'s first invocation will not be immediately, but also wait for the given delay. So if you want the first invocation to be after 5 seconds, you will need to subtract the 1000 of the setInterval() from the 5000 of the setTimeout(). (Or alternatively invoke the repeated function manually immediately.)

    function doSomething() {
      let a = 1;
      let intervalId = setInterval(() => {
        console.log(a);
        if (a < 6) {
          a++;
        } else {
          clearInterval(intervalId);
        }
      }, 1000);
    }
    
    setTimeout(doSomething, 4000);