Bird
Raised Fist0
Node.jsframework~20 mins

setTimeout and clearTimeout in Node.js - Practice Problems & Coding Challenges

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
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 will this Node.js code output?
Consider the following code snippet using setTimeout and clearTimeout. What will be printed to the console?
Node.js
const timer = setTimeout(() => {
  console.log('Hello after 1 second');
}, 1000);

clearTimeout(timer);

console.log('Timer cleared');
ATimer cleared
BNo output
CHello after 1 second
DHello after 1 second\nTimer cleared
Attempts:
2 left
💡 Hint
Think about what clearTimeout does to a scheduled timer.
state_output
intermediate
2:00remaining
What is the value of count after this code runs?
Look at this Node.js code using setTimeout. What will be the final value of count after 1500 milliseconds?
Node.js
let count = 0;

const timer = setTimeout(() => {
  count += 1;
}, 1000);

setTimeout(() => {
  clearTimeout(timer);
}, 500);

setTimeout(() => {
  console.log(count);
}, 1500);
A1
Bundefined
C0
DThrows an error
Attempts:
2 left
💡 Hint
When is the timer cleared compared to when it would run?
📝 Syntax
advanced
2:00remaining
Which option correctly cancels a repeating timer?
You want to stop a repeating timer created with setInterval. Which code snippet correctly cancels it?
Node.js
const intervalId = setInterval(() => {
  console.log('Tick');
}, 1000);

// Which line correctly stops the interval?
AstopInterval(intervalId);
BclearInterval(intervalId);
CcancelTimeout(intervalId);
DclearTimeout(intervalId);
Attempts:
2 left
💡 Hint
Remember the difference between setTimeout and setInterval cancellation functions.
🔧 Debug
advanced
2:00remaining
Why does this timer never stop?
This code is intended to print 'Hello' every second and stop after 3 seconds. Why does it keep printing forever?
Node.js
const timer = setTimeout(function repeat() {
  console.log('Hello');
  setTimeout(repeat, 1000);
}, 1000);

setTimeout(() => {
  clearTimeout(timer);
  console.log('Stopped');
}, 3000);
ABecause clearTimeout only cancels the first timer, but new timers keep being created inside repeat.
BBecause clearTimeout is called too late after 3 seconds.
CBecause setTimeout cannot be used recursively.
DBecause the timer variable is not declared with let or const.
Attempts:
2 left
💡 Hint
Look at how many timers are created and which one is cleared.
🧠 Conceptual
expert
3:00remaining
What is the behavior of this code snippet?
Analyze this Node.js code. What will be the output and why?
Node.js
let count = 0;

const timer = setTimeout(() => {
  console.log('Timeout 1:', count);
}, 1000);

const timer2 = setTimeout(() => {
  console.log('Timeout 2:', count);
}, 1500);

count = 5;

clearTimeout(timer);

setTimeout(() => {
  console.log('Final count:', count);
}, 2000);
ATimeout 1: 5\nFinal count: 5
BTimeout 1: 0\nTimeout 2: 5\nFinal count: 5
CTimeout 1: 5\nTimeout 2: 5\nFinal count: 5
DTimeout 2: 5\nFinal count: 5
Attempts:
2 left
💡 Hint
Consider which timers are cleared and when the variable count changes.

Practice

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

Solution

  1. Step 1: Understand setTimeout purpose

    setTimeout schedules a function to run once after a delay in milliseconds.
  2. Step 2: Compare options with definition

    Only Runs a function once after a specified delay matches this behavior. Runs a function repeatedly at fixed intervals describes setInterval, the option about stopping a running function immediately is incorrect, and the option about scheduling when the program ends is incorrect.
  3. Final Answer:

    Runs a function once after a specified delay -> Option D
  4. Quick Check:

    setTimeout = run once after delay [OK]
Hint: Remember: setTimeout runs once after delay [OK]
Common Mistakes:
  • Confusing setTimeout with setInterval
  • Thinking setTimeout repeats automatically
  • Believing setTimeout stops functions
2. Which of the following is the correct syntax to cancel a timeout set by setTimeout?
easy
A. stopTimeout(timeoutId);
B. cancelTimeout(timeoutId);
C. clearTimeout(timeoutId);
D. clearInterval(timeoutId);

Solution

  1. Step 1: Recall the function to cancel setTimeout

    The correct function to cancel a timeout is clearTimeout with the timeout ID.
  2. Step 2: Check each option's validity

    Only clearTimeout(timeoutId); uses the correct function name. cancelTimeout and stopTimeout do not exist. clearInterval(timeoutId); is for intervals, not timeouts.
  3. Final Answer:

    clearTimeout(timeoutId); -> Option C
  4. Quick Check:

    Cancel timeout = clearTimeout [OK]
Hint: Use clearTimeout with the ID from setTimeout [OK]
Common Mistakes:
  • Using clearInterval to cancel setTimeout
  • Using non-existent functions like cancelTimeout
  • Not passing the timeout ID to clearTimeout
3. What will be the output of the following code?
const id = setTimeout(() => console.log('Hello'), 1000);
clearTimeout(id);
console.log('Done');
medium
A. Done
B. Hello\nDone
C. Hello
D. No output

Solution

  1. Step 1: Analyze setTimeout and clearTimeout usage

    The timeout is set to print 'Hello' after 1 second, but immediately cleared with clearTimeout(id).
  2. Step 2: Determine what prints immediately

    The console.log('Done') runs immediately, so only 'Done' is printed.
  3. Final Answer:

    Done -> Option A
  4. Quick Check:

    clearTimeout cancels delayed output [OK]
Hint: clearTimeout stops delayed code; immediate logs still run [OK]
Common Mistakes:
  • Expecting 'Hello' to print after clearTimeout
  • Thinking both 'Hello' and 'Done' print
  • Confusing order of console logs
4. Identify the error in this code snippet:
const timer = setTimeout(() => console.log('Run'), 2000);
clearTimeout(timer);
clearTimeout(timer);
medium
A. No error; calling clearTimeout multiple times is safe
B. setTimeout callback will still run despite clearTimeout
C. Missing parentheses in clearTimeout calls
D. Calling clearTimeout twice causes an error

Solution

  1. Step 1: Understand clearTimeout behavior

    Calling clearTimeout multiple times on the same ID does not cause errors; it safely ignores subsequent calls.
  2. Step 2: Check syntax and callback execution

    Syntax is correct, and the callback will not run because the timeout was cleared.
  3. Final Answer:

    No error; calling clearTimeout multiple times is safe -> Option A
  4. Quick Check:

    Multiple clearTimeout calls are safe [OK]
Hint: clearTimeout can be called repeatedly without error [OK]
Common Mistakes:
  • Thinking multiple clearTimeout calls cause errors
  • Believing callback runs after clearTimeout
  • Confusing syntax with missing parentheses
5. You want to print "Start", then after 2 seconds print "Middle", but if a user clicks a button before 2 seconds, cancel "Middle" and print "Cancelled" immediately. Which code snippet correctly implements this behavior? Options: A)
console.log('Start');
const id = setTimeout(() => console.log('Middle'), 2000);
button.onclick = () => {
  clearTimeout(id);
  console.log('Cancelled');
};
B)
console.log('Start');
setTimeout(() => console.log('Middle'), 2000);
button.onclick = () => {
  clearTimeout();
  console.log('Cancelled');
};
C)
console.log('Start');
const id = setTimeout(() => console.log('Middle'), 2000);
button.onclick = () => {
  console.log('Cancelled');
  clearTimeout();
};
D)
console.log('Start');
const id = setTimeout(() => console.log('Middle'), 2000);
button.onclick = () => {
  clearInterval(id);
  console.log('Cancelled');
};
hard
A. clearTimeout called without ID, so timeout not canceled
B. Correctly cancels timeout and prints Cancelled on click
C. Prints Cancelled then calls clearTimeout without ID, so timeout not canceled
D. Uses clearInterval instead of clearTimeout, so fails

Solution

  1. Step 1: Check timeout setup and cancellation

    Correctly cancels timeout and prints Cancelled on click, which stores the timeout ID and uses it in clearTimeout inside the click handler, correctly canceling the delayed print.
  2. Step 2: Verify order of console logs and function calls

    Correctly cancels timeout and prints Cancelled on click prints 'Start' immediately, then 'Cancelled' if clicked before 2 seconds, preventing 'Middle' from printing.
  3. Step 3: Analyze other options for errors

    The second option does not store the timeout ID and calls clearTimeout() without an argument (no effect). The third option stores the ID but calls clearTimeout() without passing the ID (no effect). The fourth option uses clearInterval(id), which cannot cancel a timeout.
  4. Final Answer:

    Correctly cancels timeout and prints Cancelled on click -> Option B
  5. Quick Check:

    Use clearTimeout with stored ID to cancel delayed action [OK]
Hint: Store timeout ID and clearTimeout with it on event [OK]
Common Mistakes:
  • Not passing timeout ID to clearTimeout
  • Using clearInterval instead of clearTimeout
  • Calling clearTimeout without arguments