JavaScriptEasy
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
Timeoutobject (which also hasref()/unref()). clearTimeoutandclearIntervalare 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 action2function 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}910sendWithUndo("first email"); // will be sent11const undo = sendWithUndo("second email");12undo(); // cancelled: second email1314// Debounce relies on clearTimeout15function debounce(fn, wait) {16 let timer;17 return (...args) => {18 clearTimeout(timer); // cancel the previous pending call19 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 saved2627// Clearing an already-fired or invalid id is harmless28clearTimeout(123456);29clearTimeout(undefined);3031await 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.