Beginner LevelJavaScript & TypeScript
How do setTimeout and setInterval work and how do you clear them?
❓ Interview Prompt: Explain timer IDs, delay scheduling, clearTimer methods, and timer drift/unreliability in single-threaded JS.
Timers in JavaScript schedule code to run asynchronously after a specified delay:
1. setTimeout(callback, delayMs, ...args):
Executes callback once after delayMs milliseconds.
•
Cancel with
clearTimeout(timerId).2. setInterval(callback, intervalMs, ...args):
Executes callback repeatedly every intervalMs milliseconds until canceled.
•
Cancel with
clearInterval(intervalId).Key Warning:
Timers are non-blocking macrotasks. The delay specifies the minimum time before execution, not exact timing, because long synchronous tasks on the Call Stack block execution.
Code Implementation Example
javascript
// Schedule timer
const timerId = setTimeout((name) => {
console.log(`Hello ${name}`);
}, 1000, 'Alice');
// Cancel timer before it executes
clearTimeout(timerId);
// Recurring timer with auto-cleanup after 3 ticks
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Tick ${count}`);
if (count >= 3) {
clearInterval(intervalId); // Stop recurring timer!
}
}, 500);💡Timer creation with argument passing and clearing interval timers on count threshold.
🎯 Interview Key Takeaway
Timers return a numeric ID used with clearTimeout/clearInterval to cancel execution before memory leaks occur.
#Timers#Async#Event Loop#Beginner
Back to all JavaScript & TypeScript Questions→