0
0
Node.jsframework~15 mins

setInterval and clearInterval in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Using setInterval and clearInterval in Node.js
📖 Scenario: You are building a simple timer in Node.js that prints a message every second. You want to start the timer, count how many times the message has printed, and stop the timer after a certain number of prints.
🎯 Goal: Create a Node.js script that uses setInterval to print a message every second, counts the prints, and uses clearInterval to stop after 5 prints.
📋 What You'll Learn
Create a variable to count the number of prints
Create an interval using setInterval that prints a message every second
Stop the interval after 5 prints using clearInterval
💡 Why This Matters
🌍 Real World
Timers like this are used in real applications to perform tasks repeatedly, such as updating a clock, checking for new messages, or refreshing data.
💼 Career
Understanding how to use timers and control their lifecycle is important for backend and frontend developers to manage asynchronous tasks and improve user experience.
Progress0 / 4 steps
1
Create a counter variable
Create a variable called count and set it to 0.
Node.js
Need a hint?

Use let count = 0; to create a variable that can change.

2
Create an interval to print a message every second
Create a variable called intervalId and assign it the result of setInterval. Inside setInterval, write a function that prints 'Hello every second' and increases count by 1. Set the interval time to 1000 milliseconds.
Node.js
Need a hint?

Use setInterval(() => { ... }, 1000) to run code every second.

3
Stop the interval after 5 prints
Inside the setInterval function, add an if statement that checks if count is equal to 5. If yes, call clearInterval(intervalId) to stop the interval.
Node.js
Need a hint?

Use if (count === 5) { clearInterval(intervalId); } to stop the timer.

4
Add a final message after stopping the interval
After calling clearInterval(intervalId), add a line inside the if block that prints 'Timer stopped after 5 prints.'.
Node.js
Need a hint?

Use console.log('Timer stopped after 5 prints.'); inside the if block.