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 secondsStore the timer ID in a variable called
timerIdCreate a variable called
cancelAfter set to 2000 (milliseconds)Use
setTimeout again to cancel the first timer after cancelAfter milliseconds using clearTimeoutEnsure 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