The setInterval function in JavaScript is to call a function or calculate an expression according to the specified cycle time. Its syntax is "setInterval(func,ms)". The return value is an ID, which can be passed to "clearInterval" function to cancel execution.
Usage example
You can pop up every three seconds (3000 milliseconds) by calling a named function "Hello":
var myVar; function myFunction() { myVar = setInterval(alertFunc, 3000); } function alertFunc() { alert("Hello!"); }
Display the current time (the setInterval() method will execute the function once every second, similar to the watch function):
var myVar = setInterval(function(){ myTimer() }, 1000); function myTimer() { var d = new Date(); var t = d.toLocaleTimeString(); document.getElementById("demo").innerHTML = t; }
Use clearInterval() to stop the execution of setInterval:
var myVar = setInterval(function(){ myTimer() }, 1000); function myTimer() { var d = new Date(); var t = d.toLocaleTimeString(); document.getElementById("demo").innerHTML = t; } function myStopFunction() { clearInterval(myVar); }
Use setInterval() and clearInterval() to create a dynamic progress bar:
function move() { var elem = document.getElementById("myBar"); var width = 0; var id = setInterval(frame, 10); function frame() { if (width == 100) { clearInterval(id); } else { width++; elem.style.width = width + '%'; } } }
Recommended tutorial: "JavaScript"
The above is the detailed content of How to use setInterval function in Javascript?. For more information, please follow other related articles on the PHP Chinese website!