Open In App

What is setTimeout() function in JavaScript ?

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:

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




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

Output:



Article Tags :