Bird
0
0

Consider this code:

medium📝 component behavior Q5 of 15
Node.js - Timers and Scheduling
Consider this code:
let count = 0;
const intervalId = setInterval(() => {
  console.log(count);
  count++;
  if (count > 2) clearInterval(intervalId);
}, 1000);
What will be the output?
ALogs 0, 1, 2, 3, then stops.
BLogs 0, 1, 2, then stops.
CLogs 0, 1, 2, 3, 4, ... forever.
DThrows an error because clearInterval is inside the callback.
Step-by-Step Solution
Solution:
  1. Step 1: Understand setInterval with clearInterval

    The interval logs count every second and increments it. When count exceeds 2, it clears the interval.
  2. Step 2: Trace output values

    Logs 0, 1, 2, then when count becomes 3, clearInterval stops further calls.
  3. Final Answer:

    Logs 0, 1, 2, then stops. -> Option B
  4. Quick Check:

    clearInterval stops after count > 2 = B [OK]
Quick Trick: clearInterval stops setInterval when condition met [OK]
Common Mistakes:
  • Expecting logs beyond 2
  • Thinking clearInterval causes error inside callback
  • Confusing count condition logic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes