JavaScript(JS) setInterval()
setInterval()
is a JavaScript method that allows you to repeatedly run a block of code at a specified interval. It takes two arguments: a function to execute and a time interval in milliseconds.
Here's an example of using setInterval()
to log the current time to the console every second:
function logTime() { console.log(new Date().toLocaleTimeString()); } setInterval(logTime, 1000);Source:www.theitroad.com
In this example, the logTime
function is defined to log the current time to the console using the console.log()
method. The setInterval()
method is called with the logTime
function as the first argument and the time interval of 1000 milliseconds (1 second) as the second argument. This causes the logTime
function to be called every second, repeatedly logging the current time to the console.
It's important to note that setInterval()
will continue to execute the specified function at the specified interval until it is stopped. To stop the execution of setInterval()
, you can use the clearInterval()
method, passing it the ID returned by the setInterval()
method.
Here's an example of using clearInterval()
to stop the execution of setInterval()
after a specified number of iterations:
let count = 0; function logCount() { console.log(count); count++; if (count >= 5) { clearInterval(intervalID); } } const intervalID = setInterval(logCount, 1000);
In this example, the logCount
function is defined to log the current value of the count
variable to the console, increment the count
variable by 1, and stop the execution of setInterval()
if the count
variable reaches 5 or higher. The setInterval()
method is called with the logCount
function as the first argument and the time interval of 1000 milliseconds (1 second) as the second argument. The ID returned by the setInterval()
method is stored in the intervalID
variable, which is then passed to the clearInterval()
method when the count
variable reaches 5.