JavaScript setTimeout method

The setTimeout method is used to “delay” a function or code execution by specifying the time in milliseconds. This is quite useful in certain situations, for example, redirecting from one website to another website while notifying a user: “you will be redirected to another site in 10 seconds” etc.

The setTimeout method takes two parameters, that are mandatory, as shown in the syntax below:

How to use the JavaScript setTimeout?

Following is the syntax to use the setTimeout method:

window.setTimeout(Function_name()|Code, time_in_milliseconds);

Or you can use it simply as follows:

setTimeout(Function_name()|Code, time_in_milliseconds);

The window.setTimeout or (setTimeout) method executes the given function only once. You can use the setInterval method to execute the function repeatedly.

Following are a few examples of using JavaScript setTimeout method.

A setTimeout example to redirect to another website

Following is a JS setTimeout example where we will execute a function to redirect to another website. As you click on the button, it will execute JS function on the onclick event of the button element.

The function will execute the window.setTimeout method that will redirect to the google.com website after five seconds gap.

Experience this example online

setTimeout JavaScript example to display an alert

Rather using a function, you can simply place the code in the setTimeout method. In this example, an alert will be displayed as setTimeout method executes after three seconds after you clicked the button. Click on image or link to see it live:

Experience this example online

Javascript clearTimeout to clear the timer example

You can use JavaScript clearTimeout method to clear the timer set in setTimeout function. This will prevent the function or code given in setTimeout function to execute. The setTimeout method returns the numeric value which is the time specified in the function.

In the following example, two buttons are given; one to execute setTimeout method. This will redirect to another domain in five seconds. The other button will execute clearTimeout method. If you click on the first button and then press the second button (that stops the function by using clearTimeout) before five seconds it will prevent redirection.

The other button will execute the clearTimeout method. If you click on the first button and then press the second button (that stops the function by using clearTimeout) before five seconds it will prevent redirection.

Experience this example online

The left button, as you click on it, will redirect to google.com in five seconds. If you click the right button, before five seconds, it will stop redirection by using the clearTimeout method.

Also see: Javascript innerHTML | Javascript redirect method