DEV Community

ABISHEK M
ABISHEK M

Posted on

setTimeout() in JavaScript

setTimeout() is a built-in JavaScript function that is used to execute a function after a specified amount of time. It is commonly used when we want to delay some code from running immediately.

The basic syntax of setTimeout() is:

setTimeout(function, delay);
Enter fullscreen mode Exit fullscreen mode

Here, function is the code that we want to execute later, and delay is the amount of time we want to wait. The delay is measured in milliseconds. For example, 1000 milliseconds is equal to 1 second.

setTimeout(() => {
    console.log("Hello");
}, 3000);
Enter fullscreen mode Exit fullscreen mode

In this example, "Hello" will be printed after approximately 3 seconds.

One important thing to understand is that setTimeout() does not stop or pause JavaScript while waiting.

For example:

console.log("Start");

setTimeout(() => {
    console.log("Hello");
}, 2000);

console.log("End");
Enter fullscreen mode Exit fullscreen mode

The output will be:

Start
End
Hello
Enter fullscreen mode Exit fullscreen mode

First, "Start" is printed. Then setTimeout() schedules the function to run later. JavaScript continues with the next line, so "End" is printed. After approximately 2 seconds, "Hello" is executed.

We can also cancel a timeout using clearTimeout().

const timer = setTimeout(() => {
    console.log("Hello");
}, 5000);

clearTimeout(timer);
Enter fullscreen mode Exit fullscreen mode

Here, the scheduled function is cancelled, so "Hello" will not be printed.

setTimeout() is useful in many real-world situations. For example, it can be used to show a notification after a few seconds, hide a message after some time, delay an action, or create simple animations.

In conclusion, setTimeout() is used to schedule a function to run later after a specified delay. It is an important concept for understanding asynchronous JavaScript.

Top comments (0)