Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   How to Use setTimeout in JavaScript

JavaScript - How to Use setTimeout in JavaScript

The setTimeout function is a native JavaScript function. It sets a timer (a countdown set in milliseconds) for an execution of a callback function, calling the function upon completion of the timer.

JavaScript’s setTimeout method can prove handy in various situations. For example, you can use setTimeout to play a sound one second after a winner was declared in an online game, or when a “Welcome” popup needs to be displayed two seconds after a user visits your site. The setTimeout method is as versatile as you need it to be.

The setTimeout function runs only once per call, meaning that after the execution of the callback function completes, setTimeout has finished its job.

Note: For a countdown that restarts automatically, executing the callback function several times with a timed break between each execution, please see setInterval().

Syntax

The basic and most commonly used syntax for this function is:

setTimeout(callback function, delay in milliseconds)

In this code, callback function is the function to be executed, and the delay is the time delay (in milliseconds) before the callback function is executed. The following example code demonstrates how to use this function:

function greet() {
 alert('Welcome!');
}
setTimeout(greet, 2000); //execute greet after 2000 milliseconds (2 seconds)

In the example above, alert() is the callback function that will be executed 2 seconds after setTimeout() is invoked, resulting in a browser popup saying Welcome!.

setTimeout() lets us assign as many arguments as necessary to the callback function. For example, let’s say we want to welcome John, our logged-in user, with a custom message. We simply append arguments to the end of the setTimeout parameter list:

setTimeout(callback function, delay in milliseconds, arg1)

You can see an example of this code at work below:

const loggedInUser = 'John';
function greet(userName) {
  alert('Welcome ' + userName + '!');
}
setTimeout(greet, 2000, loggedInUser);

In the example above, a popup will appear after 2 seconds saying: “Welcome John!”. The name “John” was pulled from our const variable loggedInUser, and added to the callback as a function parameter.

Warning- Do not pass arguments to the callback directly!

With the above code, you may be tempted to pass the arguments directly as parameters to your callback method. For example:

setTimeout(greet(loggedInUser), 2000);

This is a logic error. With the above line of code, the callback function is executed immediately and the delay parameter is ignored completely. This is because we have not passed a function object as a callback method to setTimeout(), but rather we are setting the function’s return value as the callback method, which causes JavaScript to not complete our timeout request.

To fix this error, simply modify your call pattern to append function arguments to the end of the setTimeout() parameter list. This lets the callback method be sent as an object, and ensures the method is called properly after the specified time has elapsed.

clearTimeout – Stop the execution of setTimeout

In some cases, you may find that you need to cancel a Timeout that has already started. The setTimeout() method returns a key that lets us refer to the pending execution of the callback function. We can use this key as an “abort” key, giving us control over the timeout mechanism itself. This key value is provided as the return value from the setTimeout() method:

const timerId = setTimeout(greet, 5000, loggedInUser);

In the example above, timerId will contain a key that can be used to refer to the timer in progress. To cancel the timeout, this key can be passed to the clearTimeout() function as a parameter

function _clear_() {
  clearTimeout(timerId);
}

When the clearTimeout() function executes, the timer will be cancelled and its callback function will not be executed. You can use this to cancel any timeout in progress, provided you recorded the return value from the setTimeout() function.

 

Related Articles: 

JavaScript – How to Change The Page URL

JavaScript – How to Format Date

JavaScript – How to Set an HTML Element’s Class

Get AI Code Completions for Your IDE