Timers: setTimeout & setInterval
Timers let you schedule code to run after a delay (setTimeout) or repeatedly at intervals (setInterval). Essential for animations, auto-save, polling, countdowns, and timed notifications.
Timers Explained
- setTimeout(callback, ms) — Run once after delay: setTimeout(() => alert('Hi'), 2000) (2 seconds)
- setInterval(callback, ms) — Run repeatedly every ms: setInterval(() => tick(), 1000) (every second)
- clearTimeout(id) — Cancel a timeout before it fires
- clearInterval(id) — Stop an interval from repeating
- Return value — Both return a numeric ID used for clearing
- 0ms delay — setTimeout(fn, 0) doesn't run immediately! It queues after current code finishes (event loop)
Timers Code
// setTimeout — run once after delay
console.log("Start");
const timeoutId = setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
// Cancel before it fires
// clearTimeout(timeoutId);
// setInterval — run repeatedly
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Tick #${count}`);
// Stop after 5 ticks
if (count >= 5) {
clearInterval(intervalId);
console.log("Timer stopped!");
}
}, 1000);
// Real-world: debounced auto-save
let saveTimeout;
function autoSave(content) {
clearTimeout(saveTimeout); // cancel previous
saveTimeout = setTimeout(() => {
console.log("Auto-saving:", content);
}, 1000); // save 1s after last change
}
autoSave("Draft 1");
autoSave("Draft 2"); // cancels previous, only this one saves
// setTimeout 0 — deferred execution
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
// Output: A, C, B (B is queued, runs after current code)Tip
Tip
Use setTimeout(fn, 0) to defer code execution until after the current call stack clears. This is useful for letting the browser render updates before running heavy code. clearTimeout and clearInterval prevent memory leaks.
Delay is minimum, not exact. Always clean up.
Common Mistake
Warning
Not clearing intervals when they're no longer needed. setInterval runs forever until cleared. Store the interval ID and call clearInterval when the component unmounts or the timer should stop, or you'll create memory leaks.
Practice Task
Note
Build a countdown timer: (1) Use setInterval to update every second. (2) Display minutes:seconds format. (3) Stop at 0 with clearInterval. (4) Add pause/resume buttons.
Quick Quiz
Key Takeaways
- Timers let you schedule code to run after a delay (setTimeout) or repeatedly at intervals (setInterval).
- setTimeout(callback, ms) — Run once after delay: setTimeout(() => alert('Hi'), 2000) (2 seconds)
- setInterval(callback, ms) — Run repeatedly every ms: setInterval(() => tick(), 1000) (every second)
- clearTimeout(id) — Cancel a timeout before it fires