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

codeTap to expand ⛶
1// setTimeout
2const timeoutId = setTimeout(() => {
3 console.log("This runs after 2 seconds");
4}, 2000);
5clearTimeout(timeoutId); // Cancel before it fires
6
7// setInterval
8let count = 0;
9const intervalId = setInterval(() => {
10 count++;
11 console.log(`Tick ${count}`);
12 if (count >= 5) clearInterval(intervalId); // Stop after 5 ticks
13}, 1000);
14
15// setTimeout with arguments
16setTimeout((name, greeting) => {
17 console.log(`${greeting}, ${name}!`);
18}, 1000, "Alice", "Hello");
19
20// 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 completes
25 }
26 tick();
27}
28poll(async () => {
29 console.log("Polling...", new Date().toLocaleTimeString());
30}, 2000);
31
32// Debounce pattern
33function debounce(fn, delay) {
34 let timer;
35 return function(...args) {
36 clearTimeout(timer);
37 timer = setTimeout(() => fn.apply(this, args), delay);
38 };
39}
40
41// Throttle pattern
42function 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:

  1. Build a countdown timer that displays seconds remaining
  2. Create a typing effect that reveals text one character at a time
  3. Implement a polling function that fetches data every 5 seconds
  4. 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 cycle

  • setInterval can drift — if the callback takes longer than the interval, executions stack up. Use recursive setTimeout instead

  • Forgetting 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 performance

  • The 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.