What is clearTimeout?

clearTimeout(id) cancels a timer created by setTimeout before it fires, using the id that setTimeout returned; calling it with an id that already fired or is invalid does nothing.

Where it is essential

  • Debounce: every new call clears the previous timer and starts a new one.
  • Component cleanup: clear pending timers when a component unmounts (in a React effect's cleanup), otherwise the callback may update state that no longer exists.
  • Cancelling delayed actions: "undo send" within 5 seconds, hiding a tooltip unless the pointer leaves, auto-logout warnings.
  • Timeouts for async work: clear the timeout when the real operation finishes first.

Details

  • In browsers the id is a positive integer. In Node it is a Timeout object (which also has ref()/unref()).
  • clearTimeout and clearInterval are technically interchangeable in browsers, but use the matching one for clarity.
  • Keep the id in a variable that outlives the scheduling call (a closure, a ref, or an object property).

Common bug

Storing the timer id in a variable that is recreated on every render (a plain variable in a React function component). The cleanup then clears the wrong id. Use the effect cleanup or a useRef.

Code example

js
1// Undo send: cancel a delayed action
2function sendWithUndo(message, delay = 50) {
3 const timer = setTimeout(() => console.log("sent:", message), delay);
4 return () => {
5 clearTimeout(timer);
6 console.log("cancelled:", message);
7 };
8}
9
10sendWithUndo("first email"); // will be sent
11const undo = sendWithUndo("second email");
12undo(); // cancelled: second email
13
14// Debounce relies on clearTimeout
15function debounce(fn, wait) {
16 let timer;
17 return (...args) => {
18 clearTimeout(timer); // cancel the previous pending call
19 timer = setTimeout(() => fn(...args), wait);
20 };
21}
22const save = debounce((text) => console.log("saved draft:", text), 30);
23save("H");
24save("He");
25save("Hello"); // only this one is saved
26
27// Clearing an already-fired or invalid id is harmless
28clearTimeout(123456);
29clearTimeout(undefined);
30
31await new Promise((r) => setTimeout(r, 120));

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app