Discover JavaScript Timers

setTimeout()

When writing JavaScript code, you might want to delay the execution of a function.

This is the job of setTimeout. You specify a callback function to execute later, and a value expressing how later you want it to run, in milliseconds:

function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)
setTimeout
(() => {
// runs after 2 seconds }, 2000); function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)
setTimeout
(() => {
// runs after 50 milliseconds }, 50);

This syntax defines a new function. You can call whatever other function you want in there, or you can pass an existing function name, and a set of parameters:

const const myFunction: (firstParam: any, secondParam: any) => voidmyFunction = (firstParam: anyfirstParam, secondParam: anysecondParam) => {
  // do something
};

// runs after 2 seconds
function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)
setTimeout
(const myFunction: (firstParam: any, secondParam: any) => voidmyFunction, 2000, firstParam, secondParam);

setTimeout returns a Timeout instance in Node.js, whereas in browsers it returns a numeric timer ID. This object or ID can be used to cancel the scheduled function execution:

const const timeout: numbertimeout = function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)
setTimeout
(() => {
// should run after 2 seconds }, 2000); // I changed my mind function clearTimeout(id: number | undefined): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout)
clearTimeout
(const timeout: numbertimeout);

Zero delay

If you specify the timeout delay to 0, the callback function will be executed as soon as possible, but after the current function execution:

function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)
setTimeout
(() => {
var console: Consoleconsole.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
('after ');
}, 0); var console: Consoleconsole.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(' before ');

This code will print

before
after

This is especially useful to avoid blocking the CPU on intensive tasks and let other functions be executed while performing a heavy calculation, by queuing functions in the scheduler.

Some browsers (IE and Edge) implement a setImmediate() method that does this same exact functionality, but it's not standard and unavailable on other browsers. But it's a standard function in Node.js.

setInterval()

setInterval is a function similar to setTimeout, with a difference: instead of running the callback function once, it will run it forever, at the specific time interval you specify (in milliseconds):

function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval)
setInterval
(() => {
// runs every 2 seconds }, 2000);

The function above runs every 2 seconds unless you tell it to stop, using clearInterval, passing it the interval id that setInterval returned:

const const timeout: numbertimeout = function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval)
setInterval
(() => {
// runs every 2 seconds }, 2000); function clearInterval(id: number | undefined): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval)
clearInterval
(const timeout: numbertimeout);

It's common to call clearInterval inside the setInterval callback function, to let it auto-determine if it should run again or stop. For example this code runs something unless App.somethingIWait has the value arrived:

const const interval: numberinterval = function setInterval(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval)
setInterval
(() => {
if (App.somethingIWait === 'arrived') { function clearInterval(id: number | undefined): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval)
clearInterval
(const interval: numberinterval);
} // otherwise do things }, 100);

Recursive setTimeout

setInterval starts a function every n milliseconds, without any consideration about when a function finished its execution.

If a function always takes the same amount of time, it's all fine:

setInterval working fine

Maybe the function takes different execution times, depending on network conditions for example:

setInterval varying duration

And maybe one long execution overlaps the next one:

setInterval overlapping

To avoid this, you can schedule a recursive setTimeout to be called when the callback function finishes:

const const myFunction: () => voidmyFunction = () => {
  // do something

  function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)
setTimeout
(const myFunction: () => voidmyFunction, 1000);
}; function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout)
setTimeout
(const myFunction: () => voidmyFunction, 1000);

to achieve this scenario:

Recursive setTimeout

setTimeout and setInterval are available in Node.js, through the Timers module.

Node.js also provides setImmediate(), which is equivalent to using setTimeout(() => {}, 0), mostly used to work with the Node.js Event Loop.

Час на читання
2 хв
Автори
Долучитися
Редагувати цю сторінку
Зміст
  1. setTimeout()
  2. Zero delay
  3. setInterval()
  4. Recursive setTimeout