0
0
Node.jsframework~15 mins

setTimeout and clearTimeout in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use console.log to show a message before the cancel timeout runs.