How to Use setTimeout in JavaScript

  • 4 min read
  • December 25, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

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

The 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().

SetTimeout JS – 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 canceled 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

Related Posts

How to Get an Object’s Keys and Values in JavaScript

How to Get an Object’s Keys and Values in JavaScript

In JavaScript, getting the keys and values that comprise an object is very easy. You can retrieve each object’s keys, values, or both combined into an

How to Use the Assignment Operator in JavaScript

How to Use the Assignment Operator in JavaScript

The Assignment operator is used to assign a value to a variable. Assignment (=) The assignment operator simply assigns the value of the right operand to

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement