JavaScript setTimeout

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 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:

Syntax of setTimeout

Following is the syntax to use 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.

Javascript 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: “Click here to execute setTimeout Javascript“, it will execute JS function on the onclick event of the button element. The function will execute window.setTimeout method that will redirect to the 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 setTimeout method. In this example, an alert will be displayed as JS setTimeout executes after three seconds, as you clicked the button.

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 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.

Experience this example online

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

Also see: Javascript innerHTML | Javascript redirect method

Was this article helpful?

Related Articles

Leave A Comment?