How to use setTimeout in JavaScript

Key takeaways:

  • The setTimeout() function is a built-in JavaScript method that allows to execute a specified block of code or a function after a designated time delay, measured in milliseconds.

  • Syntax: setTimeout(function|code, delay_time, arg1, arg2, ...)

  • The return value is a numeric timer ID, which can be used with clearTimeout() to cancel the execution.

  • If no delay is provided, the function is executed immediately in the next event cycle.

  • We can schedule functions to execute after a specified delay, pass arguments to those functions, and even use strings to evaluate code.

  • Use clearTimeout() with the timer ID to cancel a scheduled function execution before it runs.

One of the essential features of JavaScript is its ability to handle asynchronous operations, allowing us to execute code after a specified delay. In this Answer, we will learn how to use the setTimeout() method in JavaScript. So, let’s dive in and learn together!

What is setTimeout()?

The setTimeout() function is a built-in JavaScript method that allows to execute a specific block of code or a function after a designated time delay, measured in milliseconds. This function is particularly useful when we want to delay actions, such as showing messages or executing tasks at specified intervals.

Syntax

Let’s take a look at the syntax of this method:

setTimeout(function|code, [delay_time], [arg1], [arg2], ...);

Parameters

The parameters of the setTimeout() method are:

  • function|code is the function or string value to be executed after the delay time expires.

  • delay_time is the time in milliseconds (1000 milliseconds = 1 second), after which the function will be executed. The value is 0 by default.

  • arg1, arg2, ... are extra arguments passed to the function.

Return value

The return value of setTimeout() is a numeric timer ID, which can be used later to clear the timeout using the clearTimeout() method.

Example: Schedule a function

Let’s say we need to print a message after one second.

  • JavaScript
Console
Scheduling a function for one second

In the above code:

  • Lines 1–3: We define a welcome() function that prints the string “Welcome to Educative!” to the console.

  • Line 5: We call the setTimeout() with a delay of 1000 milliseconds (one second) and call the welcome() function.

Running the above code will print “Welcome to Educative!” after one second.

Example: Using arguments with setTimeout()

Let’s see how we can use setTimeout() in a practical example.

  • JavaScript
Console
Passing an argument to the scheduled function

In the above code:

  • Line 1: We print a welcome message to the console.

  • Lines 3–6: We define a function named greet() that takes one argument, name, and logs a personalized greeting to the console.

  • Line 7: We use setTimeout() to call greetUser() after 1000 milliseconds (one second) and pass the argument 'Bob'.

Running the above code will print “Welcome to Educative!” first and then “Hi Bob!” after one second.

Example: Passing string instead of a function

If we pass a string as the first argument, then JavaScript will execute the string using the eval() method.

Console
Passing string as an argument instead of a funciton

In the above code, instead of a function, we pass the console.log() command as an argument in string. It will print the same output as the previous example.

Cancel the scheduled function’s execution

Sometimes, we may want to cancel a timeout before it executes. We can achieve this using the clearTimeout() function. When we call setTimeout(), it will return a unique numeric ID. We can then pass this ID to the clearTimeout() function to cancel the execution of the scheduled function.

Console
Clearing the scheduled message

In the above code:

  • Line 7: We set a timeout to call greet after 1000 milliseconds (one second) and store the timer ID in the variable uniqueTimeOutId.

  • Line 8: We call clearTimeout() with uniqueTimeOutId to cancel the execution of greet().

When we execute the above code, the message will not be printed because we’ve cleared the scheduled function.

Example: Zero delay setTimeOut()

When we don’t send the delay time, then the delay time is set to zero, meaning that the timeout function will execute immediately in the next event cycle.

Console
Zero delay setTimeout

When JavaScript executes the test() function:

  • It detects setTimeout() and pushes the printMsg() function to the event loopAn area to store functions to be executed next. The function that is inserted first in the event loop will be executed first..

  • After completion of the test() function, JavaScript will check if there is any function available in the event loop. JavaScript finds the printMsg() function is waiting for its execution, so JavaScript will execute the printMsg() function.

Example: try-catch in setTimeout()

In setTimeout(), the exception on the callback function will not be caught if we surround the setTimeout() with try-catch.

function test(){
const a = 7;
a = 10;
}
try{
setTimeout(test, 100);
} catch(e) {
console.log(e);
}

The code above will throw an error because the test() function will be executed after 100 milliseconds. Before executing the test() function, the JavaScript engine has already left the try-catch area.

To handle this, we need to catch the exception inside the callback function.

function test(){
const a = 7;
a = 10;
}
setTimeout(function() {
try {
test()
} catch(e) {
console.log(e);
}
}, 100);

In this example, we wrap the call to test() inside a try-catch block within the setTimeout() callback function, allowing us to catch the error properly.

Example: this in setTimeout()

When we pass a method reference to setTimeout(), the window inside the callback function is the this keyword.

let user = {
detail : { age: 20},
printAge() {
console.log(this);
console.log(this.detail.age);
}
}
user.printAge(); // print user object and 20
setTimeout(user.printAge, 1000); // print window and throws an error

In the above code, when setTimeout() executes printAge(), this keyword refers to the global object instead of the user object, resulting in an error.

To solve this, use an arrow function as a callback function.

let user = {
detail : { age: 20},
printAge() {
console.log(this);
console.log(this.detail.age);
}
}
setTimeout(() => {
user.printAge();
}, 1000);
// or use normal function
setTimeout(function() {
user.printAge();
}, 1000);

Practical example: Debounce

Based on an event we can register an operation to be executed after some delay. If the same event occurs again, then the old registered operation is deleted and a new operation is registered. Debounce groups multiple events into a single event.

Consider an input box. Once the user types something in the input, we need to update the content based on the input value. We can use debounce here because we don’t need to fetch data for each letter typed by the user; instead, we wait for some milliseconds and then send a request.

Type something in the text box below to see the code in action:

  • HTML
  • SCSS
  • JavaScript
Console
Grouping multiple events into a single event

In the above code:

  • Line 1: We select the input element from the DOM.

  • Line 2: We declare a variable timerId to hold the ID of the timeout.

  • Lines 3–5: The fetchData() function logs the current value of the input box to the console.

  • Lines 6–12: We add an event listener for the input event. If the timerId is already set, we clear the previous timeout. We then set a new timeout to call fetchData() after 300 milliseconds.

This approach ensures that fetchData() is only executed after the user has stopped typing for 300 milliseconds, reducing unnecessary requests and improving performance.

By using setTimeout() effectively, we can control the timing of function execution in our JavaScript applications, making the code more efficient and user-friendly.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

What does the setTimeout() method do in JavaScript?

A)

Executes code synchronously

B)

Executes code after a specified delay

C)

Stops all code execution

D)

Runs a function immediately without delay

Question 1 of 30 attempted

Conclusion

The setTimeout() function in JavaScript handles asynchronous operations and controls the timing of code execution. By understanding its syntax, parameters, and various use cases, such as scheduling functions, managing errors, and optimizing performance through debouncing, we can write more efficient and responsive applications. Learning setTimeout() will enhance our JavaScript skill set, allowing for better user experience and interaction in web development. Whether we’re managing UI events or processing data, effective use of setTimeout() can significantly improve the application’s functionality.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do you delay 5 seconds in JavaScript?

To delay execution in JavaScript for 5 seconds, you can use the setTimeout() function. Here’s an example:

setTimeout(() => {
  console.log("This message is displayed after a 5-second delay.");
}, 5000); // 5000 milliseconds = 5 seconds

In this code, the message will be logged to the console after a delay of 5 seconds.


How to wait for 1 second in JavaScript?

To wait for 1 second in JavaScript, you can similarly use setTimeout():

setTimeout(() => {
  console.log("This message is displayed after a 1-second delay.");
}, 1000); // 1000 milliseconds = 1 second

This will log the message to the console after a 1-second delay.


What is the difference between setTimeout and setInterval?

The primary difference between setTimeout and setInterval lies in their functionality:

  • setTimeout(): This function is used to execute a function or a block of code once after a specified delay (in milliseconds). After the delay, it runs the function and does not repeat it unless called again.

    setTimeout(() => {
      console.log("This message is displayed once after 2 seconds.");
    }, 2000); // Executes once after 2 seconds
    
  • setInterval(): This function is used to execute a function or block of code repeatedly, at specified intervals (in milliseconds). The function will continue to execute at the given interval until clearInterval() is called.

    const intervalId = setInterval(() => {
      console.log("This message is displayed every 2 seconds.");
    }, 2000); // Executes every 2 seconds
    
    // To stop the interval after 10 seconds:
    setTimeout(() => {
      clearInterval(intervalId);
      console.log("Interval cleared.");
    }, 10000); // Clears the interval after 10 seconds
    

In summary, use setTimeout() for a one-time delay and setInterval() for repeated execution at regular intervals.


Free Resources