Student-friendly HTML, CSS, and JavaScript reference with examples
setInterval() runs a function repeatedly at a fixed time interval.
setInterval(function() {
console.log("Hello!");
}, 2000);
This prints “Hello!” every 2 seconds (2000 milliseconds).
Stopping it:
Save the return value and pass it to clearInterval() to stop:
const timer = setInterval(function() {
console.log("Running...");
}, 1000);
// Later, stop it:
clearInterval(timer);
Common use: polling an API to keep data updated:
setInterval(async function() {
const response = await fetch(url);
const data = await response.json();
renderPage(data);
}, 2000);