What is setInterval, what is it for, and how does it work?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #Asynchronicity #JS Basics

Quick Answer

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.


What is setInterval

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.

Syntax

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.

How it works: The Event Loop

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.

  1. Calling setInterval passes the timer to the Web APIs.
  2. The main JavaScript thread continues to execute without being blocked.
  3. When the timer expires, the callback is placed in the callback queue.
  4. The Event Loop checks if the call stack is empty.
  5. As soon as the stack becomes empty, the callback from the queue is moved to the stack and executed.
  6. After the 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.


Usage Examples

1. Simple Timer

let counter = 0;
 
const intervalId = setInterval(() => {
  counter++;
  console.log(`Seconds passed: ${counter}`);
 
  if (counter >= 5) {
    clearInterval(intervalId);
    console.log("Timer stopped.");
  }
}, 1000);

Console output:

  1. “Seconds passed: 1”
  2. “Seconds passed: 2”
  3. “Seconds passed: 3”
  4. “Seconds passed: 4”
  5. “Seconds passed: 5”
  6. “Timer stopped.”

2. Passing Arguments to the Callback

function greet(name, phrase) {
  console.log(`${phrase}, ${name}!`);
}
 
setInterval(greet, 2000, "Alexander", "Good day");
// Every 2 seconds, it will output: "Good day, Alexander!"

3. Canceling a Timer with clearInterval

If 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);

Practice Problems

Problem 1

// 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);
Answer **Answer:** The code will output numbers starting from 1 at an interval of 100 ms. After 500 ms (when `i` is approximately 5), `setTimeout` will change `i` to 1000. The next `setInterval` call will increment `i` to 1001 and log it. The code will run forever because there is no `clearInterval`.

Problem 2

// 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();
Answer
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.