01 / 21

setTimeout &
setInterval

Master JavaScript's timing functions to schedule code execution: run once after a delay, or repeat on a fixed cycle.

JavaScript

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.

setTimeout
Runs a function once after a specified delay in milliseconds.
setInterval
Runs a function repeatedly at a fixed time interval.

Why Do We Need Timers?

Timers unlock time-based behavior in your programs. Without them, everything would execute instantly, top to bottom.

Delayed Actions
Show a tooltip after 2 seconds, auto-dismiss a notification.
Polling
Check a server for new messages every 5 seconds.
Animation
Update a progress bar or countdown clock at regular intervals.

Timers and the Event Loop

Call Stack main() setTimeout() Web APIs Timer: 2000ms counting down... Done → Callback Queue Callback Queue callback() Event Loop Moves callback to stack when empty

The setTimeout Syntax

// Syntax const timerId = setTimeout(callback, delay, ...args); // Example: log after 2 seconds const id = setTimeout(() => { console.log("Hello after 2s!"); }, 2000); // Cancel before it fires clearTimeout(id);
callback
The function to execute after the delay.
delay
Time in milliseconds (\(1000\text{ms} = 1\text{s}\)).
timerId
A numeric ID used to cancel with clearTimeout.

The setInterval Syntax

// Syntax const intervalId = setInterval(callback, interval, ...args); // Example: log every 3 seconds const id = setInterval(() => { console.log("Tick!"); }, 3000); // Stop the interval clearInterval(id);

setTimeout vs setInterval

setTimeout 0ms delay fires once done setInterval 0ms interval interval interval fires fires fires... setInterval repeats until clearInterval() is called

Step-by-Step Timer Checklist

1
Decide: once or repeating? Use setTimeout for one-time delays, setInterval for repeating tasks.
2
Write the callback function. This is the code that will run when the timer fires.
3
Set the delay in milliseconds. Remember: \(1000\text{ms} = 1\text{s}\). Convert as needed.
4
Store the returned ID. You will need it to cancel the timer later.
5
Clean up! Call clearTimeout or clearInterval when the timer is no longer needed.

Example 1: Delayed Greeting

function greet(name) { console.log(`Hello, ${name}!`); } // Greet after 3 seconds, passing "Alice" as argument const id = setTimeout(greet, 3000, "Alice"); console.log("This runs first!"); // Output order: // "This runs first!" // (3 seconds later) "Hello, Alice!"

Example 2: Countdown Timer

let seconds = 10; const countdownId = setInterval(() => { console.log(seconds); seconds--; if (seconds < 0) { clearInterval(countdownId); console.log("Liftoff!"); } }, 1000);

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.

let count = 0; function tick() { console.log("Tick:", count++); if (count < 5) { setTimeout(tick, 1000); // schedule next } } tick(); // start the chain

Recursive vs setInterval Timing

setInterval cb slow cb queued! cb 100ms 100ms 100ms Recursive setTimeout cb 100ms delay slow cb 100ms delay cb Recursive setTimeout guarantees the gap between executions

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.

setTimeout(() => { console.log("Timer!"); // might fire at ~1005ms }, 1000); // Heavy computation blocks the main thread for (let i = 0; i < 1e9; i++) {} // takes ~2s // "Timer!" won't log until loop finishes (~2s)

Passing Arguments to Timers

Both setTimeout and setInterval accept extra arguments after the delay. These are passed directly to the callback function.

function add(a, b) { console.log(a + b); } // Pass 3 and 7 as arguments to add() setTimeout(add, 1000, 3, 7); // After 1s, logs: 10

Common Mistakes

Calling the function
Writing setTimeout(greet(), 1000) calls greet immediately and passes its return value. Use setTimeout(greet, 1000) instead.
Forgetting clearInterval
An interval without clearInterval runs forever, causing memory leaks and unexpected behavior.
Using strings as callbacks
Writing setTimeout("alert('hi')", 1000) uses eval() internally. Always pass a function reference.

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

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?