0
0
Node.jsframework~5 mins

setInterval and clearInterval in Node.js

Choose your learning style9 modes available
Introduction

setInterval lets you run a task repeatedly every set time. clearInterval stops that repeated task.

You want to show a clock that updates every second.
You need to check for new messages every few seconds.
You want to repeat a task until a condition is met.
You want to animate something by updating it regularly.
Syntax
Node.js
const intervalId = setInterval(() => {
  // code to run repeatedly
}, delayInMilliseconds);

clearInterval(intervalId);
setInterval returns an ID you use to stop it later with clearInterval.
delayInMilliseconds is how often the code runs, in milliseconds (1000 ms = 1 second).
Examples
This prints a message every 2 seconds until stopped.
Node.js
const intervalId = setInterval(() => {
  console.log('Hello every 2 seconds');
}, 2000);

// To stop later:
clearInterval(intervalId);
This counts up every second and stops after 5 times.
Node.js
let count = 0;
const intervalId = setInterval(() => {
  count++;
  console.log(`Count: ${count}`);
  if (count === 5) {
    clearInterval(intervalId);
    console.log('Stopped interval');
  }
}, 1000);
Sample Program

This program prints "Tick" with a number every second. After 3 ticks, it stops and prints "Interval cleared".

Node.js
let counter = 0;
const intervalId = setInterval(() => {
  counter++;
  console.log(`Tick ${counter}`);
  if (counter === 3) {
    clearInterval(intervalId);
    console.log('Interval cleared');
  }
}, 1000);
OutputSuccess
Important Notes

Always save the ID returned by setInterval to clear it later.

If you forget to clearInterval, the task keeps running and can cause problems.

Summary

setInterval runs code repeatedly at set time intervals.

clearInterval stops the repeated running using the ID from setInterval.

Use these to repeat tasks like updating clocks or animations.