Open In App

What is the purpose of setTimeout() function in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In JavaScript, the setTimeout() function is utilized to introduce a delay or to execute a particular function after a specified amount of time has passed. It is part of the Web APIs provided by browsers and Node.js, allowing asynchronous execution of code.

Syntax:

setTimeout(function, milliseconds, arg1, arg2, ...);

Parameters:

  • function: After the specified time period, this is the function that is executed.
  • milliseconds: The delay time is expressed in milliseconds.
  • arg1arg2: If needed, these are the optional parameters.

Cancellation of setTimeout()

JavaScript provides a corresponding function called clearTimeout() to cancel a scheduled timeout before it gets executed.

Example: In this example, we have shown the cancellation of settimeout..

Javascript




function delayedFunction() {
    console.log("This won't be executed due to clearTimeout");
}
 
let timeoutId = setTimeout(delayedFunction, 2000);
 
// Cancel the setTimeout before it executes
clearTimeout(timeoutId);
 
console.log("Timeout canceled");


Purpose of setTimeout()

In JavaScript, the setTimeout() function is utilized to introduce a delay or to execute a particular function after a specified amount of time has passed. It is part of the Web APIs provided by browsers and Node.js, allowing asynchronous execution of code.

Example: Below is the example of settimeout.

Javascript




console.log("Start");
 
setTimeout(function() {
    console.log("Delayed log after 2000 milliseconds");
}, 2000);
 
console.log("End");


Output:

Start
End
Delayed log after 2000 milliseconds

Explanation:

  • The setTimeout() function takes two parameters: a callback function and a time delay in milliseconds.
  • In the example, after the initial “Start” and “End” logs, the setTimeout() is set to execute the callback function (delayed log) after 2000 milliseconds (2 seconds).
  • The rest of the code continues executing without waiting for the delay, demonstrating the asynchronous nature of setTimeout().
  • After the specified delay, the callback function is invoked, resulting in the “Delayed log after 2000 milliseconds” message being logged to the console.

Use Cases:

  1. Delaying Execution: It can be used to introduce delays in code execution, useful for scenarios like animations, timed events, or deferred operations.
  2. Asynchronous Operations: When combined with callback functions, it facilitates asynchronous behavior, enabling non-blocking code execution.
  3. Timeouts in Web Development: It’s commonly employed in web development for handling timeouts, such as showing a notification after a certain time or refreshing content.


Last Updated : 08 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads