setTimeout & setInterval
📖 Concept
setTimeout executes a function ONCE after a specified delay (in milliseconds). setInterval executes a function REPEATEDLY at a specified interval.
Both return an ID that can be used with clearTimeout()/clearInterval() to cancel them.
Important: The delay is the MINIMUM time, not guaranteed exact time. If the call stack is busy, the callback waits.
🏠 Real-world analogy: setTimeout is like setting an alarm for one time. setInterval is like setting a recurring alarm (every morning at 7am).
💻 Code Example
1// setTimeout2const timeoutId = setTimeout(() => {3 console.log("This runs after 2 seconds");4}, 2000);5clearTimeout(timeoutId); // Cancel before it fires67// setInterval8let count = 0;9const intervalId = setInterval(() => {10 count++;11 console.log(`Tick ${count}`);12 if (count >= 5) clearInterval(intervalId); // Stop after 5 ticks13}, 1000);1415// setTimeout with arguments16setTimeout((name, greeting) => {17 console.log(`${greeting}, ${name}!`);18}, 1000, "Alice", "Hello");1920// Recursive setTimeout (preferred over setInterval for precise timing)21function poll(fn, interval) {22 async function tick() {23 await fn();24 setTimeout(tick, interval); // Next tick starts AFTER fn completes25 }26 tick();27}28poll(async () => {29 console.log("Polling...", new Date().toLocaleTimeString());30}, 2000);3132// Debounce pattern33function debounce(fn, delay) {34 let timer;35 return function(...args) {36 clearTimeout(timer);37 timer = setTimeout(() => fn.apply(this, args), delay);38 };39}4041// Throttle pattern42function throttle(fn, limit) {43 let inThrottle = false;44 return function(...args) {45 if (!inThrottle) {46 fn.apply(this, args);47 inThrottle = true;48 setTimeout(() => (inThrottle = false), limit);49 }50 };51}
🏋️ Practice Exercise
Mini Exercise:
- Build a countdown timer that displays seconds remaining
- Create a typing effect that reveals text one character at a time
- Implement a polling function that fetches data every 5 seconds
- Build a simple stopwatch with start, stop, and reset
⚠️ Common Mistakes
setTimeout(fn, 0)doesn't execute immediately — it's deferred to the next macrotask cyclesetIntervalcan drift — if the callback takes longer than the interval, executions stack up. Use recursive setTimeout insteadForgetting to clear intervals — memory leak! Always store the ID and clear on cleanup
Passing a string to setTimeout (
setTimeout('alert(1)', 1000)) — uses eval, security risk and worse performanceThe timer ID is just a number — accidentally using it instead of clearing it is a common bug
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for setTimeout & setInterval. Login to unlock this feature.