📅  最后修改于: 2023-12-03 15:05:11.388000             🧑  作者: Mango
Setinterval is a built-in function in JavaScript that allows you to execute a function or a code block repeatedly with a fixed time delay between each execution. It is a popular choice for creating animations, timers, and periodic updates on web pages.
The syntax for setinterval() function is as follows:
var intervalID = setInterval(func, delay, [arg1, arg2, ...]);
Where:
intervalID
: a unique ID that identifies the interval. You can use this ID later to cancel the interval using the clearInterval()
function.func
: the function that you want to execute repeatedly. This can be either a named or an anonymous function.delay
: the time interval between each executed function, in milliseconds.[arg1, arg2, ...]
: Optional arguments that you want to pass to the function.Here is a simple example that uses setinterval() to display a counter:
var count = 0;
var intervalID = setInterval(function() {
console.log(count);
count++;
}, 1000);
In this example, the code block inside the anonymous function is executed every 1000 milliseconds (1 second), and the count
variable is incremented and logged to the console.
To stop the execution of a setinterval(), you need to use the clearInterval()
function, passing it the ID of the interval you want to cancel. Here's an example:
var intervalID = setInterval(function() {
// code block here
}, 1000);
// cancel the interval after 5 seconds
setTimeout(function() {
clearInterval(intervalID);
}, 5000);
In this example, we create an interval that executes a code block every 1000 milliseconds, and we set a timeout of 5000 milliseconds (5 seconds) to cancel the interval by calling the clearInterval()
function with the interval's ID.