Skip to main content

What does setTimeout() do and return?

What setTimeout() does

setTimeout() is a task-scheduling function that:

  1. registers a callback (a function) in the Web API or the Node.js Timer API,
  2. starts a timer for a given time (in milliseconds),
  3. once that time elapses - adds the callback to the macrotask queue (Task Queue),
  4. 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 to callback.

Example

javascript
console.log('Start'); setTimeout(() => { console.log('After 2 seconds'); }, 2000); console.log('End');

Order of execution:

javascript
Start End After 2 seconds

Why?

  • JS first runs all the synchronous code.
  • setTimeout only 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 timer

After 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 B

Because 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 seconds

The 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 second

SUMMARY

What it doesReturnsWhere it runsQueue
Schedules a function to run after a given delayA numeric timer IDInside the Web API (browser) or the Node Timer APIMacrotasks (Task Queue)
Can be canceledclearTimeout(timerId)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.