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(timeoutId);
The ID comes from setTimeout(). Clearing an already-fired or unknown timeout ID has no useful effect and does not throw an error.
let timerId;
function resetReminder() {
clearTimeout(timerId);
timerId = setTimeout(() => {
console.log("Time is up");
}, 5000);
}
Debouncing waits until rapid events stop before doing expensive work.
let debounceId;
input.addEventListener("input", () => {
clearTimeout(debounceId);
debounceId = setTimeout(() => {
runSearch(input.value);
}, 300);
});
After cancelling a timer, assigning null to your own variable can make application state clearer.
clearTimeout(timerId);
timerId = null;
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.
clearTimeout() without retaining the ID.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.