Cancel or Reset JavaScript Timers with clearTimeout()

clearTimeout() cancels a one-time timer created by setTimeout(). A common pattern is to clear the existing timeout before scheduling a replacement, which effectively resets the timer.

let timerId = setTimeout(remind, 5000);
clearTimeout(timerId);

clearTimeout() Syntax Top ↑

clearTimeout(timeoutId);

The ID comes from setTimeout(). Clearing an already-fired or unknown timeout ID has no useful effect and does not throw an error.

Reset a Timer by Clearing and Scheduling Again Top ↑

let timerId;
function resetReminder() {
  clearTimeout(timerId);
  timerId = setTimeout(() => {
    console.log("Time is up");
  }, 5000);
}

Use clearTimeout() to Debounce Repeated Input Top ↑

Debouncing waits until rapid events stop before doing expensive work.

let debounceId;
input.addEventListener("input", () => {
  clearTimeout(debounceId);
  debounceId = setTimeout(() => {
    runSearch(input.value);
  }, 300);
});

Keep Timer State Easy to Understand Top ↑

After cancelling a timer, assigning null to your own variable can make application state clearer.

clearTimeout(timerId);
timerId = null;

Stopping a Recursive setTimeout() Chain Top ↑

For a recursive timer, clear the most recent timeout ID and also make sure the callback cannot schedule a new timeout after you have requested a stop.

let stopped = false;
let timerId;
function tick() {
  if (stopped) return;
  timerId = setTimeout(tick, 1000);
}

See recursive timers and stopwatch timing.

Common clearTimeout() Mistakes Top ↑

  • Calling clearTimeout() without retaining the ID.
  • Creating multiple timeouts and storing only the newest ID.
  • Assuming cancellation reverses work already done by the callback.
  • Using a string callback instead of a function.

setTimeout() Date Reference




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer