What does setTimeout() do and return?
What setTimeout() does
setTimeout() is a task-scheduling function that:
- registers a callback (a function) in the Web API or the Node.js Timer API,
- starts a timer for a given time (in milliseconds),
- once that time elapses - adds the callback to the macrotask queue (Task Queue),
- the callback is executed only when the call stack is free.
Syntax
javascript
setTimeout(callback, delay, ...args);Parameters:
callback- the function to execute;delay- the delay in milliseconds (does not guarantee an exact time!);...args- extra arguments passed tocallback.
Example
javascript
console.log('Start');
setTimeout(() => {
console.log('After 2 seconds');
}, 2000);
console.log('End');Order of execution:
javascript
Start
End
After 2 secondsWhy?
- JS first runs all the synchronous code.
setTimeoutonly schedules the task.- After 2000 ms the callback goes into the task queue.
- When the stack is empty, the Event Loop runs the callback.
What setTimeout() returns
The function returns a numeric timer identifier - a unique ID that can be used to cancel execution with clearTimeout().
Example:
javascript
const timerId = setTimeout(() => {
console.log('Will not have time to run');
}, 5000);
clearTimeout(timerId); // cancel the timerAfter calling clearTimeout(timerId) the callback never runs.
Important details
1. Minimum delay
Even setTimeout(..., 0) does not run instantly:
javascript
setTimeout(() => console.log('B'), 0);
console.log('A');Prints:
javascript
A
BBecause even with delay = 0, the callback is added to the macrotask queue, and only runs after the stack is cleared and all microtasks (Promise.then, etc.) have run.
2. Does not guarantee an exact time
If JS is busy running another function, the timer "is late".
javascript
setTimeout(() => console.log('I am late!'), 1000);
const start = Date.now();
while (Date.now() - start < 5000) {} // block the thread for 5 secondsThe callback fires after 5 seconds, not after 1 - because the stack was busy.
3. Arguments can be passed
javascript
setTimeout((a, b) => {
console.log(a + b);
}, 1000, 5, 7);
// -> prints 12 after a secondSUMMARY
| What it does | Returns | Where it runs | Queue |
|---|---|---|---|
| Schedules a function to run after a given delay | A numeric timer ID | Inside the Web API (browser) or the Node Timer API | Macrotasks (Task Queue) |
| Can be canceled | clearTimeout(timerId) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.