How to use the setTimeout() function in JavaScript

Introduction

Scheduling allows you to perform tasks after a time-lapse. JavaScript handles this with the setTimeout() function. With setTimeout(), we can delay an action until the timer elapses or prompt an action to happen after a certain time has elapsed (often in seconds). These actions can range from; triggering an action if a user has been on a page for a recorded amount of time, prompting to take an action after a set time has expired, or even triggering action through user-inputted functions.

Initializing the setTimeout() function can be done with this line of code:

setTimeout(function, milliseconds);

Here the first parameter; the function to be called by the setTimeout() will be triggered once the second optional parameter; the delay or time (in milliseconds) specified elapses. If the delay is not specified, the default is set to zero. The setTimeout() also takes in optional parameters to pass to the function.

Example

An example would be a function call that sends a greeting alert if a user has been on the site for 5 seconds:

// this program displays an alert using setTimeout method after 5 seconds

function hey() {
    alert("Hey there!");
}

setTimeout(hey, 5000);

In this example, we can see the function hey() will display an alert that says "Hey there" when called by the setTimeout() function after 5000 milliseconds (5 seconds). The time parameter of the setTimeout() function is measured in milliseconds and dividing by 1000 would convert it to seconds, you can then proceed with the manipulation of time for your function call to happen.

Note that

Note that setTimeout() is an asynchronous function and thus allows other functions to run while waiting to execute. In other words, it does not hinder the execution of other functions in the queue.

The function passed to setTimeout() does not need to be executed just after the given milliseconds, this second parameter is the minimum time after which the browser will enqueue that function into the callback queue, It is unpredictable how much time it has to wait for pushed into the JS engine call stack.

An interesting example to illustrate this would be listed on mdn web docs, here the third message gets pushed to the top of the queue and executed first once the delay condition is met, and then the second message before the first.

setTimeout(() => {
  console.log("this is the first message");
}, 5000);
setTimeout(() => {
  console.log("this is the second message");
}, 3000);
setTimeout(() => {
  console.log("this is the third message");
}, 1000);

Return Value of setTimeout()

The setTimeout() returns a positive integer value or number that is the timerID (id of the timer), this id identifies the call made to the setTimeout() and is used with clearTimeout() to cancel the timeout.

clearTimeout()

setTimeout() can be canceled using clearTimeout(). This would need the id returned by the setTimeout() to know which method to cancel.

const timeoutId = setTimeout(function(){
    console.log("Hey there");
}, 2000);

clearTimeout(timeoutId);
console.log(`Timeout ID ${timeoutId} has been cleared`);

Calling the clearTimeout() ensures that the setTimeout function does not run.

Conclusion

In summary, setTimeout() is an asynchronous function that helps you execute functions or code after a time period has elapsed. this does not inhibit the execution of other lines of code. setTimeout() can be prevented or canceled using the id of the setTimeout() with clearTimeout.