Implement ClearAllInterval in JavaScript

JavaScript has a timer function setInterval which repeatedly executes a function after a specified amount of time. Each setInterval method returns a unique id which can be used to cancel or clear the interval using clearInterval.

It is a common interview question where we are asked to implement a method clearAllInterval which will clear all the running setInterval’s.

Similarly, as we have implemented the clearAllTimeout method, the same logic can be used to implement the clearAllInterval.

First, to clear all the intervals at once, we need to store all of them so that they can be cleared one by one using the clearInterval method.

Thus we can define a global variable intervalIds that will store the ids of the setIntervals and override the existing setInterval function to push the ids in this global variable.

//to store all the interval ids
window.intervalIds = [];

//origianl interval function
const originalIntervalFn = window.setInterval;

//overriding the origianl
window.setInterval = function(fn, delay){
  const id = originalIntervalFn(fn, delay);
  //storing the id of each interval
  intervalIds.push(id);
  return id;
}

//clear all interval
window.clearAllInterval = function(){
  while(intervalIds.length){
    clearInterval(intervalIds.pop());
  }
}
Input:
setInterval(() => {
  console.log("Hello");
}, 2000);


setInterval(() => {
  console.log("Hello2");
}, 500);

clearAllInterval();

setInterval(() => {
  console.log("Hello3");
}, 1000)

Output:
"Hello3" // after every ~1 sec 

If you notice, here we have added a global variable intervalIds which we are using to store the ids of each setInterval and later to cancel all of them. Using the global variable is bad practice as it can be overridden.

One thing you could do over here is to wrap these inside a closure or higher-order function or an Object to keep it restricted.

This way we won’t be interfering with existing methods and can still get our work done.

const MY_TIMERS = {
    intervalIds : [],//global interval id's arrays
    //create a MY_TIMERS's interval
    setInterval : function(fn,delay){
        let id = setInterval(fn,delay);
        this.intervalIds.push(id);
        return id;
    },
    //MY_TIMERS's clearAllTimeout
    clearAllInterval : function(){
        while(this.intervalIds.length){
          clearTimeout(this.intervalIds.pop());
        }
    }
};
Input:
MY_TIMERS.setInterval(() => {
  console.log("Hello");
}, 2000);

MY_TIMERS.setInterval(() => {
  console.log("Hello2");
}, 500);

MY_TIMERS.clearAllInterval();

MY_TIMERS.setInterval(() => {
  console.log("Hello3");
}, 1000);

Output:
"Hello3" // after every ~1 sec