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
Using setTimeout and clearTimeout in Node.js
📖 Scenario: You are creating a simple Node.js script that waits a few seconds before showing a message. Sometimes, you want to stop the waiting if something changes.
🎯 Goal: Build a Node.js script that sets a timer to print a message after 3 seconds, but also allows canceling the timer before it runs.
📋 What You'll Learn
Create a timer using setTimeout that waits 3 seconds
Store the timer ID in a variable called timerId
Create a variable called cancelAfter set to 2000 (milliseconds)
Use setTimeout again to cancel the first timer after cancelAfter milliseconds using clearTimeout
Ensure the message only prints if the timer is not canceled
💡 Why This Matters
🌍 Real World
Timers are used in Node.js to delay actions, like waiting for a response or scheduling tasks.
💼 Career
Understanding timers and how to cancel them is important for writing efficient asynchronous code in Node.js applications.
Progress0 / 4 steps
1
Create a timer with setTimeout
Create a variable called timerId and assign it the result of setTimeout that waits 3000 milliseconds and then runs a function that logs the string 'Timer done!'.
Node.js
Hint
Use setTimeout with a function and 3000 milliseconds. Save the returned ID in timerId.
2
Add a cancelAfter variable
Add a variable called cancelAfter and set it to 2000 (milliseconds).
Node.js
Hint
Just create a variable cancelAfter and assign it the number 2000.
3
Use setTimeout to cancel the first timer
Use setTimeout with a function that calls clearTimeout(timerId) after cancelAfter milliseconds.
Node.js
Hint
Use setTimeout with a function that calls clearTimeout(timerId) after cancelAfter milliseconds.
4
Complete the script to show timer cancellation
Add a console.log statement before the cancel timeout that logs the string 'Timer will be canceled after 2000ms'.
Node.js
Hint
Use console.log to show a message before the cancel timeout runs.
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
Step 1: Understand setTimeout purpose
setTimeout schedules a function to run once after a delay in milliseconds.
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.
Final Answer:
Runs a function once after a specified delay -> Option D
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
Step 1: Recall the function to cancel setTimeout
The correct function to cancel a timeout is clearTimeout with the timeout ID.
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.
Final Answer:
clearTimeout(timeoutId); -> Option C
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
Step 1: Analyze setTimeout and clearTimeout usage
The timeout is set to print 'Hello' after 1 second, but immediately cleared with clearTimeout(id).
Step 2: Determine what prints immediately
The console.log('Done') runs immediately, so only 'Done' is printed.
Final Answer:
Done -> Option A
Quick Check:
clearTimeout cancels delayed output [OK]
Hint: clearTimeout stops delayed code; immediate logs still run [OK]
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
Step 1: Understand clearTimeout behavior
Calling clearTimeout multiple times on the same ID does not cause errors; it safely ignores subsequent calls.
Step 2: Check syntax and callback execution
Syntax is correct, and the callback will not run because the timeout was cleared.
Final Answer:
No error; calling clearTimeout multiple times is safe -> Option A
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)
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
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.
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.
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.
Final Answer:
Correctly cancels timeout and prints Cancelled on click -> Option B
Quick Check:
Use clearTimeout with stored ID to cancel delayed action [OK]
Hint: Store timeout ID and clearTimeout with it on event [OK]