setTimeout &
setInterval
Master JavaScript's timing functions to schedule code execution: run once after a delay, or repeat on a fixed cycle.
What Are JavaScript Timers?
JavaScript is single-threaded: it runs one piece of code at a time. But the browser provides Web APIs that let you schedule functions to run later, without blocking the main thread.
Why Do We Need Timers?
Timers unlock time-based behavior in your programs. Without them, everything would execute instantly, top to bottom.
Timers and the Event Loop
The setTimeout Syntax
The setInterval Syntax
setTimeout vs setInterval
Step-by-Step Timer Checklist
Example 1: Delayed Greeting
Example 2: Countdown Timer
Example 3: Recursive setTimeout
An alternative to setInterval is calling setTimeout recursively. This guarantees the delay is measured after each callback finishes, not from the start of each interval.
Recursive vs setInterval Timing
The Delay is a Minimum, Not Exact
When you write setTimeout(fn, 1000), JavaScript promises the callback will not fire before 1000ms. But it may fire after 1000ms if the call stack is busy.
Passing Arguments to Timers
Both setTimeout and setInterval accept extra arguments after the delay. These are passed directly to the callback function.
Common Mistakes
Summary Comparison
| setTimeout | setInterval | Recursive setTimeout | |
|---|---|---|---|
| Execution | Once | Repeating | Repeating |
| Cancel with | clearTimeout(id) | clearInterval(id) | Don't call setTimeout again |
| Delay guarantee | Minimum delay | Minimum between starts | Minimum between ends |
| Overlap risk | None | Yes | None |
| Best for | One-time delays | Simple repeating tasks | Async/variable-time tasks |
Question 1 of 5
What does setTimeout return?
Question 2 of 5
Consider this code:
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
What is the output order of this code?
Question 3 of 5
Which function do you call to stop a running setInterval?
Question 4 of 5
What is the bug in this code?setTimeout(myFunc(), 2000)
Question 5 of 5
Why might you prefer recursive setTimeout over setInterval for a task that makes network requests?