Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

setTimeout

Runs a function once after a delay.

Available since: Web API

Syntax

setTimeout(callback, delay, ...args)

Parameters

ParameterTypeDescription
callbackFunctionThe function to run once.
delaynumberOptional. The delay in milliseconds. 0 by default.
...argsanyOptional. Arguments for the function.

Return value

numberThe timer id — for cancelling with clearTimeout.

Examples

A delayed call:

setTimeout(() => console.log('one second later'), 1000);
 
console.log('right now');

Output:

right now
one second later

Even a zero delay runs after the current code:

setTimeout(() => console.log('timer'), 0);
 
console.log('first');
console.log('second');

Output:

first
second
timer

A pause with a promise:

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
 
console.log('start');
await sleep(300);
console.log('300 ms later');

Output:

start
300 ms later

Notes

The delay is a minimum, not an exact time: if the program is busy, the function runs later.

A common mistake is passing a call result instead of a function: setTimeout(greet(), 1000) calls greet immediately. Correct: setTimeout(greet, 1000) or setTimeout(() => greet('Anna'), 1000).

See also

  • clearTimeout — Cancels a scheduled setTimeout.
  • setInterval — Runs a function again and again at an interval.
  • Promise — A promise of a result that will be ready later: success or failure.

Related recipes

In the tutorial

  • Timers — The setTimeout and setInterval functions in JavaScript: delayed and repeated calls, arguments, cancelling a timer.

Thanks for reading!

Donate to the site — we work hard for you.