A Brief About JavaScript setInterval Method

In the previous chapter, we learned how to use the setTimeout method to execute a given function or code only once by the given time interval. If you need to execute a function or code repeatedly by given time interval, use the setInterval method of JavaScript.

The setInterval method keeps on executing a given function or code by the specified time interval until the window is closed or you can use the clearInterval method to stop it.

See an example of setInterval method

In this tutorial, we will show you examples of using the setInterval and later clearInterval method to stop executing a function, let us first look at its syntax.

Syntax to use JavaScript setInterval

This is how you can use the setInterval method:

setInterval (Function_name()|Code, time_in_milliseconds);

Or you can use it with “window” as follows:

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

Now let us look at a few examples of using the setInterval method.

The setInterval method returns a value of the timer. This is particularly useful if you need to stop executing a function by using the clearInterval method as shown in last following example.

The setInterval example of executing code

Following is an example of using JS setInterval method. We will simply display an alert with the gap of two seconds. As you close the alert, it will be triggered again and again by the two-seconds gap till you refresh the page or close the window. See working example by clicking the link or image:

Experience this example online

You can see, after clicking the button “Click here to execute setInterval” an alert will be shown after two seconds. After you close alert by clicking OK or Cross button it will be displayed again after two seconds and so on, as such we specified two seconds delay in window.setInterval method.

setInterval example of executing a function

In this example, we will use a function inside the JavaScript setInterval method. The function will also show an alert after two seconds gap.

Experience this example online

As you can see, given function showalert() is executing after two seconds and displays an alert.

JavaScript clearInterval example

Following is an example of the clearInterval method. As such, the clearInterval method is used to stop execution started by the setInterval method. In this example, we will use the ID value returned by the setInterval method in the clearInterval method.

As you click on left button, “Click here to execute setInterval Javascript” it will start showing alert after two seconds. This will keep on executing unless you click on the right button “Stop execution by clearInterval”. See working example by clicking the link or image below:

Experience this example online

As you can see the alert will keep on showing, by using setInterval method while execution is stopped by using the clearInterval method.

Also see: Javascript setTimeout