The setInterval function is used to perform a repeated action after a specified time interval. This is useful when you want to perform a task periodically in your application.
The syntax of the setInterval function is as follows:
setInterval(function, milliseconds, param1, param2, ...)
In which:
Let's see a simple example to understand how to use setInterval in JavaScript:
function printTime() {
var date = new Date();
console.log("Bây giờ là: " + date.toLocaleTimeString());
}
setInterval(printTime, 1000);
In the above example, we declare a function printTime to print the current time on the screen. This function uses the Date object to get the time and then prints the message "The current time is: " concatenated with the current time as a string. By using setInterval with a wait time of 1000 milliseconds (equivalent to 1 second), the printTime function will be called continuously every second and the current time will be printed on the console.
Similar to setTimeout, you can also use parameters in the function called by setInterval. Here is an example:
var count = 0;
function incrementCount() {
count++;
console.log("Số lần tăng: " + count);
}
setInterval(incrementCount, 2000);
In this example, we declare a variable count and a function incrementCount to increase the value of this variable after each call. The incrementCount function will print the number of times it has been called on the console. By using setInterval with a wait time of 2000 milliseconds (equivalent to 2 seconds), the incrementCount function will be called continuously every 2 seconds and the value of the count variable will increase and be printed on the console.
To stop the repetition of setInterval, you can use the clearInterval function. Here is an example:
var count = 0;
function incrementCount() {
count++;
console.log("Số lần tăng: " + count);
if (count === 5) {
clearInterval(intervalId);
}
}
var intervalId = setInterval(incrementCount, 1000);
In this example, we use the variable intervalId to store the ID of the interval created using setInterval. In the incrementCount function, we check if the value of the count variable reaches 5, we call the clearInterval function and pass the ID of the interval to stop the repetition.