Technical skill practice

setInterval in JavaScript: Run a Bounded Counter and Clear It

setInterval schedules repeated callbacks. Retain the returned timer handle and clear it when the repeated work is finished. A bounded example makes both the stopping condition and process lifetime explicit.

The task

Collect three tick numbers, cancel the timer in the third callback and print the resulting list. The task concerns callback count and cleanup, not a precision sampling interval.

Runnable Node 22 example

const assert = require('node:assert/strict');

const ticks = [];
const timer = setInterval(() => {
  ticks.push(ticks.length + 1);
  if (ticks.length === 3) {
    clearInterval(timer);
    assert.deepEqual(ticks, [1, 2, 3]);
    console.log(ticks.join(','));
  }
}, 2);

Expected output and explanation

Each callback appends the next count. The third clears the same timer that created the repetition, then checks the complete trace. With no continuing interval or other work, this script can finish.

The delay argument requests scheduling between callbacks; the output does not prove the callbacks arrived exactly two milliseconds apart. Workload and the event loop affect when scheduled work runs. In Node, a normal active interval can keep the process alive, so stopping it is part of the operation rather than optional tidying.

Output from the example

1,2,3

Pitfall to check

An async interval callback does not automatically wait for its previous Promise to finish. For work that must not overlap, schedule the next iteration after awaiting the current work instead of assuming setInterval provides that coordination.

Questions, answered

Should I use a long-running interval to test this?

No. A short count with an explicit stop can demonstrate the lifecycle without leaving background work running.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.