Categories
JavaScript Answers

How to Reset the setTimeout Timer with JavaScript?

Spread the love

Sometimes, we want to reset the setTimeout timer so that we can use it again.

In this article, we’ll look at how to reset the setTimeout timer with JavaScript.

Use the clearTimeout Function

We can use the timer created by setTimeout function with the clearTimeout function.

For instance, we can write:

let timer;

const runTimer = () => {
  timer = window.setTimeout(
    () => {
      document.body.style.backgroundColor = 'black'
    }, 3000);
}

runTimer();

document.body.onclick = () => {
  clearTimeout(timer)
  runTimer()
}

We have the timer variable that stores the timer returned by setTimeout .

Then we have the runTimer function that calls the setTimeout function with a callback that turns the page black after 3 seconds.

We assign the returned timer to timer .

Next, we call runTimer to turn the screen black after 3 seconds.

We also have a click handler assigned to the onclick property of document.body to turn the screen black after 3 seconds after clicking it.

The clearTimeout function will reset the timer and will start counting from 0 milliseconds again.

Conclusion

We can reset the timer created by setTimeout function with the clearTimeout function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *