0
0
Node.jsframework~20 mins

setInterval and clearInterval in Node.js - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Timer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this Node.js code output?
Consider the following code snippet using setInterval and clearInterval. What will be printed to the console?
Node.js
let count = 0;
const intervalId = setInterval(() => {
  count++;
  console.log(count);
  if (count === 3) {
    clearInterval(intervalId);
  }
}, 1000);
A1\n2\n3\n4 (then stops)
B1\n2\n3 (then stops)
C1\n2 (then stops)
DNo output, code throws an error
Attempts:
2 left
💡 Hint
Think about when clearInterval stops the repeated action.
📝 Syntax
intermediate
1:30remaining
Which option correctly cancels a repeating timer?
You want to stop a repeating timer created by setInterval. Which of the following code snippets correctly cancels it?
Node.js
const timer = setInterval(() => console.log('tick'), 500);
AcancelInterval(timer);
BclearTimeout(timer);
CstopInterval(timer);
DclearInterval(timer);
Attempts:
2 left
💡 Hint
Remember the function name to stop intervals is similar to the one to start them.
state_output
advanced
2:00remaining
What is the final value of counter after this code runs?
Analyze the code below. What will be the value of counter after 3500 milliseconds?
Node.js
let counter = 0;
const id = setInterval(() => {
  counter += 2;
  if (counter >= 6) {
    clearInterval(id);
  }
}, 1000);
A6
B8
C4
D0
Attempts:
2 left
💡 Hint
Count how many times the interval callback runs before stopping.
🔧 Debug
advanced
2:00remaining
Why does this code print odd numbers (1, 3, 5...) repeatedly?
Look at this code snippet. It prints '1', '3', '5', etc. every second instead of sequential numbers. What is the cause?
Node.js
let i = 0;
setInterval(() => {
  i++;
  console.log(i++);
}, 1000);
ABecause <code>i++</code> returns the value before increment, causing unexpected output.
BBecause <code>i</code> is not initialized properly.
CBecause <code>setInterval</code> callback is missing a return statement.
DBecause <code>console.log</code> is called outside the interval.
Attempts:
2 left
💡 Hint
Check how the increment operator works when used inside console.log.
🧠 Conceptual
expert
1:30remaining
What happens if you call clearInterval with an invalid ID?
In Node.js, if you call clearInterval with a value that is not a valid interval ID, what will happen?
AThe program crashes and exits.
BA runtime error is thrown immediately.
CNothing happens; the call is ignored without error.
DThe last interval created is cleared instead.
Attempts:
2 left
💡 Hint
Think about how Node.js handles invalid timer IDs safely.