How To Add A Delay In Javascript - SetTimeout Method

Sameer Saini February 25, 2022
How To Add A Delay In Javascript - SetTimeout Method

There are some scenarios where we have to delay the execution of a method by a few milliseconds or a few seconds.

A few use-cases of this could be delaying the disappearance of an alert or warning message by a few seconds.

Another example could be redirecting a webpage to another webpage and telling the user that this webpage will be redirected in X number of seconds.

Understanding The SetTimeout Method

Javascript provides us the setTimeout method which when called executes a function provided to it after the defined interval.

The setTimeout method is used to cause a delay in the execution of a function for some reason.


setInterval(function, interval);

As you can see that the setInterval method takes the first parameter as the function that needs to be executed and the second parameter is the time delay after which the function will be executed. The time interval is in milliseconds so a value of 1000 in the interval will cause a delay of 1 second.

Add A Delay In Javascript Using The SetTimeout Method

Let's look at a practical example of using the setTimeout method.

In this example, we will redirect a webpage to a different webpage after N seconds. We will set the interval in the setTimeout method and after the number of seconds are done, the function will execute.

setInterval(function () {
window.location.href = "";
}, 5000);

In the above example, we are using the window.location.href property and assigning it a new URL so that once the interval of 5 seconds has passed, the web page will redirect to this new URL.

So, we can use this delay to however we want to use it.

We can use it to dynamically change text after a definite interval, or to hide or show an element, etc.