The task is to implement a clearAllTimeout function that removes multiple timeouts at once.
The boilerplate code:
function clearAllTimeout() {
// your code here
}
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)
Loop through from 0 to the highest id, and call clearTimeout each time.
for(let i = 0; i <= highestId; i++) {
clearTimeout(i)
}
The final code is
function clearAllTimeout() {
// your code here
const highestId = setTimeout(() => {},0)
for(let i = 0; i <= highestId; i++) {
clearTimeout(i)
}
}
That's all folks!
Top comments (0)