Unlike the setTimeout() method, the setInterval() method invokes the function multiple times. This method can be written with or without the window prefix.
The commonly used syntax of setInterval() method is given below:
This method takes two parameter values function and milliseconds that are defined as follows.
function: It is the function containing the block of code that will be executed.
milliseconds: This parameter represents the length of the time interval between each execution. The interval is in milliseconds. It defines how often the code will be executed. If its value is less than 10, the value 10 is used.
How to stop the execution?
We can use the clearInterval() method to stop the execution of the function specified in setInterval() method. The value returned by the setInterval() method can be used as the argument of clearInterval() method to cancel the timeout.
Let's understand the use of setInterval() method by using some illustrations.
This is a simple example of using the setInterval() method. Here, an alert dialog box displays at an interval of 3 seconds. We are not using any method to stop the execution of the function specified in setInterval() method. So the method continues the execution of the function until the window is closed.Test it Now
After the time interval of three seconds, the output will be -
Now, there is another example of using the setInterval() method.
Here, the background color will change on every 200 milliseconds. We are not using any method to stop the execution of the function specified in setInterval() method. So the method continues the execution of the function until the window is closed.Test it Now
The background will keep changing from lightgreen to lightblue on an interval of 200 milliseconds. After 200 milliseconds, the output will be -
In the above example, we have not used any method to stop the toggling between the colors. Here, we are using the clearInterval() method to stop the toggling of colors in the previous example.
We have to click the specified stop button to see the effect.Test it Now
The color of the background will start changing after 200 milliseconds. On clicking the specified stop button, the toggling between the colors will be stopped on the corresponding background color. The output after clicking the button will be -