setInterval is a method in JavaScript that allows you to repeatedly execute a function or code snippet at a specified interval in milliseconds. It does not block the execution of the main code thread; instead, it registers a timer and continues execution. It is a primary tool for creating repetitive asynchronous operations, such as timers, animations, or periodic server requests, without freezing the user interface. To cancel the timer, clearInterval is used.
setInterval is a built-in function in browsers and Node.js that allows you to schedule the repeated execution of a function at a specific interval. It returns a numeric timer ID that can be used to cancel it.
const intervalId = setInterval(callback, delay, ...args);callback: The function to be executed.delay: The interval in milliseconds (1000 ms = 1 second). If not specified, it defaults to 0....args: Additional arguments that will be passed to the callback on each call.setInterval does not guarantee that the function will execute exactly at the specified interval. It guarantees that it will be added to the callback queue no less frequently than the delay.
setInterval passes the timer to the Web APIs.callback is placed in the callback queue.callback from the queue is moved to the stack and executed.callback finishes, the timer is reset and a new countdown begins.Important: If the execution of the callback takes longer than the delay, the next call may be queued immediately after the previous one finishes, leading to execution without a pause.
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(`Seconds passed: ${counter}`);
if (counter >= 5) {
clearInterval(intervalId);
console.log("Timer stopped.");
}
}, 1000);Console output:
function greet(name, phrase) {
console.log(`${phrase}, ${name}!`);
}
setInterval(greet, 2000, "Alexander", "Good day");
// Every 2 seconds, it will output: "Good day, Alexander!"clearIntervalIf you want to cancel a scheduled execution, use clearInterval, passing it the intervalId.
let counter = 0;
const intervalId = setInterval(() => {
console.log("This message will appear every 2 seconds.");
counter++;
if (counter > 2) {
clearInterval(intervalId);
console.log(`Timer with ID ${intervalId} has been canceled.`);
}
}, 2000);// What will this code output? Will it run forever?
let i = 0;
setInterval(() => {
i++;
console.log(i);
}, 100);
setTimeout(() => {
// What happens if we try to change i here?
i = 1000;
}, 500);// Write a function that creates a digital clock in the console,
// updating the time every second. Format: HH:MM:SS.
function digitalClock() {
// Your code
}
digitalClock();function digitalClock() {
setInterval(() => {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
console.log(`${hours}:${minutes}:${seconds}`);
}, 1000);
}Explanation: We use setInterval to execute a function every second. Inside, we get the current time, format it using padStart to add leading zeros, and log it to the console.