Bird
Raised Fist0
Node.jsframework~10 mins

setInterval and clearInterval in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - setInterval and clearInterval
Start setInterval
Schedule callback every X ms
Callback runs
Check if clearInterval called?
NoWait for next interval
Yes
Stop callback scheduling
End
setInterval schedules a function to run repeatedly every set time. clearInterval stops this repeated running.
Execution Sample
Node.js
const id = setInterval(() => {
  console.log('Tick');
}, 1000);

setTimeout(() => {
  clearInterval(id);
}, 3500);
This code prints 'Tick' every second, then stops after 3.5 seconds.
Execution Table
StepTime (ms)ActionOutputInterval Active
10setInterval scheduledYes
21000Callback runsTickYes
32000Callback runsTickYes
43000Callback runsTickYes
53500clearInterval calledNo
64000No callback (interval cleared)No
💡 clearInterval stops the repeated callback after 3.5 seconds
Variable Tracker
VariableStartAfter Step 1After Step 5Final
idundefinedInterval ID (number)Interval ID (number)Interval ID (number)
Interval ActiveNoYesNoNo
Key Moments - 2 Insights
Why does the callback stop running after step 5?
Because clearInterval is called at step 5, it stops the interval, so no more callbacks run after that (see execution_table row 5 and 6).
Does setInterval run the callback immediately at step 1?
No, setInterval schedules the callback to run after the first interval delay (1000 ms), so the first callback runs at step 2 (1000 ms).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at 2000 ms?
ANo output
B"Tick"
C"Tock"
DError
💡 Hint
Check the 'Output' column at Step 3 (2000 ms) in the execution_table.
At which step does the interval stop running callbacks?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Interval Active' column in execution_table rows 5 and 6.
If clearInterval was called at 2500 ms instead of 3500 ms, what would change?
ACallbacks would run at 1000 ms and 2000 ms only
BCallbacks would run at 1000 ms, 2000 ms, and 3000 ms
CCallbacks would run only once at 1000 ms
DCallbacks would never run
💡 Hint
Refer to variable_tracker and execution_table timing of callback runs and when clearInterval is called.
Concept Snapshot
setInterval(callback, delay) runs callback repeatedly every delay ms.
Returns an ID to clear with clearInterval(id).
clearInterval stops the repeated calls.
Callbacks start after the first delay, not immediately.
Use clearInterval to avoid infinite loops or stop timers.
Full Transcript
This example shows how setInterval schedules a function to run every 1000 milliseconds. The callback prints 'Tick' each time it runs. After 3.5 seconds, clearInterval is called to stop the repeated calls. The execution table tracks each callback run and when the interval stops. The variable tracker shows the interval ID and whether the interval is active. Key moments clarify that callbacks start after the delay and stop when clearInterval is called. The quiz tests understanding of timing and stopping intervals.

Practice

(1/5)
1. What does the setInterval function do in Node.js?
easy
A. Runs a function only once after a delay
B. Stops a running timer
C. Runs a function repeatedly at specified time intervals
D. Schedules a function to run immediately

Solution

  1. Step 1: Understand setInterval purpose

    setInterval schedules a function to run repeatedly every specified milliseconds.
  2. Step 2: Compare with other timer functions

    setTimeout runs once after delay, clearInterval stops intervals.
  3. Final Answer:

    Runs a function repeatedly at specified time intervals -> Option C
  4. Quick Check:

    setInterval = repeated execution [OK]
Hint: setInterval repeats; setTimeout runs once [OK]
Common Mistakes:
  • Confusing setInterval with setTimeout
  • Thinking clearInterval starts timers
  • Believing setInterval runs only once
2. Which of the following is the correct syntax to stop a repeating timer started with setInterval?
easy
A. clearInterval(timerId);
B. stopInterval(timerId);
C. clearTimeout(timerId);
D. cancelInterval(timerId);

Solution

  1. Step 1: Identify the function to stop intervals

    clearInterval is the built-in function to stop intervals.
  2. Step 2: Check other options

    clearTimeout stops timeouts, others are invalid functions.
  3. Final Answer:

    clearInterval(timerId); -> Option A
  4. Quick Check:

    clearInterval stops intervals [OK]
Hint: Use clearInterval with the interval ID [OK]
Common Mistakes:
  • Using clearTimeout to stop intervals
  • Using non-existent functions like stopInterval
  • Not passing the timer ID to clearInterval
3. What will the following code output to the console?
let count = 0;
const id = setInterval(() => {
  count++;
  console.log(count);
  if (count === 3) clearInterval(id);
}, 1000);
medium
A. 1 2 3 (each number printed every second, then stops)
B. 1 2 3 4 5 (prints numbers every second indefinitely)
C. Only 3 printed once after 3 seconds
D. No output because clearInterval is called immediately

Solution

  1. Step 1: Trace the interval execution

    Every 1000ms, count increases and prints. When count reaches 3, clearInterval stops it.
  2. Step 2: Understand stopping condition

    After printing 3, the interval stops, so no further output.
  3. Final Answer:

    1 2 3 (each number printed every second, then stops) -> Option A
  4. Quick Check:

    Interval runs 3 times then stops [OK]
Hint: clearInterval inside callback stops after condition [OK]
Common Mistakes:
  • Assuming it runs forever
  • Thinking clearInterval stops immediately before first print
  • Confusing setTimeout with setInterval
4. Identify the error in this code snippet:
const id = setInterval(() => {
  console.log('Hello');
});
clearInterval(id);
medium
A. No error, code works fine
B. clearInterval should be called inside the callback
C. setInterval cannot be assigned to a variable
D. Missing interval time argument in setInterval

Solution

  1. Step 1: Check setInterval syntax

    setInterval requires two arguments: function and interval time in milliseconds.
  2. Step 2: Analyze the code

    Here, the interval time is missing, causing a syntax error or unexpected behavior.
  3. Final Answer:

    Missing interval time argument in setInterval -> Option D
  4. Quick Check:

    setInterval needs delay argument [OK]
Hint: Always provide delay time in setInterval [OK]
Common Mistakes:
  • Omitting the delay argument
  • Calling clearInterval immediately without delay
  • Thinking setInterval returns undefined
5. You want to print "Tick" every second but stop after 5 ticks. Which code correctly achieves this?
hard
A. setInterval(() => { console.log('Tick'); clearInterval(timer); }, 1000);
B. let ticks = 0; const timer = setInterval(() => { ticks++; console.log('Tick'); if (ticks === 5) clearInterval(timer); }, 1000);
C. let ticks = 0; setTimeout(() => { console.log('Tick'); if (ticks < 5) ticks++; }, 1000);
D. const timer = setInterval(() => { console.log('Tick'); if (ticks === 5) clearTimeout(timer); }, 1000);

Solution

  1. Step 1: Identify correct interval and stopping logic

    let ticks = 0; const timer = setInterval(() => { ticks++; console.log('Tick'); if (ticks === 5) clearInterval(timer); }, 1000); uses setInterval with a counter and calls clearInterval after 5 ticks.
  2. Step 2: Check other options for errors

    setInterval(() => { console.log('Tick'); clearInterval(timer); }, 1000); clears immediately, let ticks = 0; setTimeout(() => { console.log('Tick'); if (ticks < 5) ticks++; }, 1000); uses setTimeout wrongly, const timer = setInterval(() => { console.log('Tick'); if (ticks === 5) clearTimeout(timer); }, 1000); uses clearTimeout instead of clearInterval.
  3. Final Answer:

    let ticks = 0; const timer = setInterval(() => { ticks++; console.log('Tick'); if (ticks === 5) clearInterval(timer); }, 1000); -> Option B
  4. Quick Check:

    Use counter and clearInterval after limit [OK]
Hint: Use a counter and clearInterval after limit [OK]
Common Mistakes:
  • Calling clearInterval immediately
  • Using clearTimeout to stop intervals
  • Using setTimeout instead of setInterval for repeated tasks