How to call JavaScript function at specified interval
In Javascript, setInterval() method call a function multiple time at a specified time interval. The interval is to be in millisecond.
setInterval() method will continue calling the function until clearInterval() method is called or windows is closed.
setInterval() method return ID, which can be used to call the clearInterval() method to stop the interval.
Syntax
setInterval(function, milliseconds, param1, param2, ...)
Parameter
function Required Define the function name that will be executed.
millisecond Required Define how often the function will be executed, the time is in a millisecond
param1, param2,.. Optional Define additional parameter to pass to the function.
See the quick example of how to use this setInterval
Example 1
We need to show time which will update every second.
See below code how to use it
<html> <head> <title></title> <meta charset="utf-8" /> <script> function showtime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); document.getElementById("spnTime").innerHTML = h + ":" + m + ":" + s; } setInterval(showtime, 1000); </script> </head> <body> <span id="spnTime"> </span> </body> </html>
Example 2
Now let's extend our example, suppose we want to stop our timer by some user action like click the "Stop Timer" button to stop the time. For cancelling the interval execution we can use cancelInterval() method.
setInterval return an id, this id passes to the cancelInterval(<id>) as a parameter. which stops the interval execution.
See the below code,
<html> <head> <title></title> <meta charset="utf-8" /> <script> function showtime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); document.getElementById("spnTime").innerHTML = h + ":" + m + ":" + s; } var idTimer = setInterval(showtime, 1000); function stopTimer() { clearInterval(idTimer); } </script> </head> <body> <span id="spnTime"> </span> <br /> <input type="button" onclick="stopTimer();" value="Stop Timer" /> </body> </html>
So above are the code example how to use setInterval() and cancelInterval().