How to call a function with a delay in JavaScript

Last updated: September 27, 2022.

Sometimes, you may not want some of your code be executed right away, but with a specified time delay.

For example, you may want to wait a specified period of time to give a process a chance to complete before processing its result.

In these situations, you can use the setTimeout() method, which is available of the global window object.

Table of contents

Using setTimeout() to delay a function call

The setTimeout() method is available on the global window object.

Because it is available on the global object, it can be called by simply calling setTimeout() rather than the longhand of window.setTimeout(). The shorthand is almost always used in practice.

The setTimeout() method accepts two arguments.

The first is a (callback) function. It is the code inside this function that will be executed with some delay.

The second argument necessary is the number of milliseconds by which the execution of the function will be delayed.

For example, below the message "Hi, sorry I'm late" is logged to the console after two seconds:

setTimeout(function() {
    console.log("Hi, sorry I'm late");
  }  
,2000);
// "message" is logged to the console after 2 seconds

Because the callback function is anonymous (i.e. it is not named), in practice it is popular to define the callback function using an arrow function, which are always anonymous.

The advantage is a slightly shorted sytnax. The functionality is the same.

For example, here’s the example above again using an arrow function this time:

setTimeout(() => {
    console.log("Sorry I'm late once again");
  }  
,2000);
// "message" is logged to the console after 2 seconds

Calling an external function

To execute a function that is already defined in your script, you pass in a reference to it in the position of the callback function.

There is no need to call it because setTimeout() calls whatever function is placed in the first argument position:

function myFunction() {
  console.log(2+2);
}

setTimeout(myFunction, 1500);
// 4 is logged to the console after 1.5 seconds

Adding arguments

If the function being called by setTimeout() accepts arguments, these should be placed after the milliseconds argument in the order they are accepted in the function:

function myFunction(x, y) {
  console.log(x+y);
}

setTimeout(myFunction, 1000, 5, 10);
// 15 is logged to the console after 1 second

Mutliple timeouts

It is possible to create multiple timeouts without a conflict between them.

This is because, each time you call setTimeout(), a unique ID is automatically assigned to that timeout.

The ID of a timeout is available as a return value when you first create it.

So you just need to save the return value:

const timer1ID = setTimeout(() => {
    console.log("T1");
},1000);

const timer2ID = setTimeout(() => {
    console.log("T2");
},1000);

const timer3ID = setTimeout(() => {
    console.log("T3");
},1000);

console.log([timer1ID, timer2ID, timer3ID]);
// Timeout IDs: [ 1, 2, 3 ]

In practice, you don't need to concern yourself with the actual values: your browser takes care of making sure the ID is always unique!

But there is an important reason why you would sometimes want to save a reference to these values: when cancelling a timeout before it has executed.

Cancelling a timeout before execution

Sometimes you may want to cancel a timeout before it has executed its callback function.

For example, you may want a user to be able to stop a page redirection before it occurs.

To do so, you can call clearTimeout() into which you need to pass in the ID of the timeout you want to cancel.

The ID of a timeout is returned as a value when it is created. To save a reference to it, store the value in a variable when calling setTimeout().

For example, if you run the code below, you can cancel the timeout that will redirect you to https://openjavascript.info after 5 seconds by clicking the button before the time is up:

<button id="cancel-timeout">Cancel redirect</button>

<script>

const btn = document.getElementById('cancel-timeout');
const url = 'https://openjavascript.info';
const countdown = 5;
 
const timerID = setTimeout(() => {
    window.location.replace(url);
},countdown*1000);

btn.addEventListener('click', () => {
    clearTimeout(timerID);
});

</script>

Summary

To delay the execution of a function in JavaScript, you can pass in the function as a first argument to the setTimeout() method. As a second argument, you specify the delay to the calling of the function in the first position in milliseconds.

If the function being called accepts arguments, these can be passed in to setTimeout() as extra arguments after the specification of the milliseconds delay.

To cancel a timeout, you call clearTimeout(), passing in the ID of the timeout to cancel. This ID is available as a return value when a timeout is first created.

Related links