The setInterval() method in JavaScript can be used to perform periodic evaluations of expressions or call a JavaScript function.
Syntax:
setInterval(function, milliseconds, param1, param2, ...)
Parameters: This function accepts the following parameters:
- function: This parameter holds the function name which to be called periodically.
- milliseconds: This parameter holds the period, in milliseconds, setInterval() calls/executes the function above.
- param1, param2, … : Some additional parameters to be passed as input parameters to function.
Return Value: This method returns the ID representing the timer set by the method. This ID can be used to clear/unset the timer by calling the clearInterval() method and passing it to this ID as a parameter.
Example: Suppose we want to create a reminder timer that goes off every 5 seconds and alerts through a JavaScript alert box.
HTML
< p > Click the button to start timer, you will be alerted every 5 seconds until you close the window or press the button to stop timer </ p > < button onclick = "startTimer()" > Start Timer </ button > < button onclick = "stopTimer()" > Stop Timer </ button > < p id = "gfg" ></ p > < script > var timer; function startTimer() { timer = setInterval(function() { document.getElementById('gfg') .innerHTML = " 5 seconds are up "; }, 5000); } function stopTimer() { document.getElementById('gfg') .innerHTML = " Timer stopped "; clearInterval(timer); } </ script > |
Output: In the above example, the setInterval() method repeatedly evaluates an expression/calls a function. The way to clear/unset the timer set by the setInterval() method is to use the clearInterval() method and pass it the ID/value returned on calling setInterval().