Open In App

What is setTimeout() function in JavaScript ?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The setTimeout function in JavaScript is a method used to introduce a delay before executing a specified function or code block. It is commonly employed for asynchronous programming and executing tasks after a certain period. It’s crucial to understand that the delay setTimeout is not guaranteed to be precise. The specified time represents the minimum delay, and the actual execution time may be slightly longer due to factors such as the JavaScript runtime’s event queue.

The setTimeout function is often used in scenarios like handling animations, managing asynchronous operations, or simulating delays. Additionally, it can be utilized in combination with closures for passing parameters to the callback function.

Syntax:

setTimeout(callback, delay);

Parameters:

  • callback: This is the function to be executed after the specified delay.
  • delay: The time, in milliseconds, to wait before executing the callback function.

Example: This example shows the use of the setTimeout() function.

Javascript




console.log("Start");
setTimeout(() => {
  console.log("Delayed message");
}, 2000);
console.log("End");


Output:

Peek-2024-02-08-13-54


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads