What if your program could remind you automatically without you lifting a finger?
Why setInterval and clearInterval in Node.js? - Purpose & Use Cases
Imagine you want to remind yourself to drink water every hour by printing a message in the console manually each time.
Manually tracking time and printing messages repeatedly is tiring, easy to forget, and your code becomes messy and hard to maintain.
Using setInterval lets your program automatically run a task repeatedly at set times, and clearInterval stops it when you want, making your code clean and reliable.
function remind() {
console.log('Drink water!');
}
// You have to call remind() yourself every hour manuallyconst id = setInterval(() => console.log('Drink water!'), 3600000); // Later, call clearInterval(id) to stop reminders
You can automate repeated tasks easily and stop them anytime without extra hassle.
A fitness app uses setInterval to remind users to stand up every 30 minutes and stops reminders when the workout ends using clearInterval.
setInterval runs code repeatedly at fixed time intervals.
clearInterval stops the repeated execution.
They help automate and control repeated tasks simply and clearly.