DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 31

The task is to implement a clearAllTimeout function that removes multiple timeouts at once.

The boilerplate code:

function clearAllTimeout() {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

To remove a specific timeout, Javascript provides clearTimeout(id). But there's no built-in function to clear multiple timeouts. For each call to an active timeout, an integer is returned which increases by one each time. So the last timeout has the highest ID.

A dummy timeout is created to get the highest ID currently in use.

const highestId = setTimeout(() => {},0)
Enter fullscreen mode Exit fullscreen mode

Loop through from 0 to the highest id, and call clearTimeout each time.

for(let i = 0; i <= highestId; i++) {
   clearTimeout(i)
}
Enter fullscreen mode Exit fullscreen mode

The final code is

function clearAllTimeout() {
  // your code here
  const highestId = setTimeout(() => {},0)
  for(let i = 0; i <= highestId; i++) {
    clearTimeout(i)
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)