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 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
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
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
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
Hint
Use console.log('Timer stopped after 5 prints.'); inside the if block.
Practice
(1/5)
1. What does the setInterval function do in Node.js?
easy
A. Runs a function only once after a delay
B. Stops a running timer
C. Runs a function repeatedly at specified time intervals
D. Schedules a function to run immediately
Solution
Step 1: Understand setInterval purpose
setInterval schedules a function to run repeatedly every specified milliseconds.
Step 2: Compare with other timer functions
setTimeout runs once after delay, clearInterval stops intervals.
Final Answer:
Runs a function repeatedly at specified time intervals -> Option C
Quick Check:
setInterval = repeated execution [OK]
Hint: setInterval repeats; setTimeout runs once [OK]
Common Mistakes:
Confusing setInterval with setTimeout
Thinking clearInterval starts timers
Believing setInterval runs only once
2. Which of the following is the correct syntax to stop a repeating timer started with setInterval?
easy
A. clearInterval(timerId);
B. stopInterval(timerId);
C. clearTimeout(timerId);
D. cancelInterval(timerId);
Solution
Step 1: Identify the function to stop intervals
clearInterval is the built-in function to stop intervals.
Step 2: Check other options
clearTimeout stops timeouts, others are invalid functions.
Final Answer:
clearInterval(timerId); -> Option A
Quick Check:
clearInterval stops intervals [OK]
Hint: Use clearInterval with the interval ID [OK]
Common Mistakes:
Using clearTimeout to stop intervals
Using non-existent functions like stopInterval
Not passing the timer ID to clearInterval
3. What will the following code output to the console?
let count = 0;
const id = setInterval(() => {
count++;
console.log(count);
if (count === 3) clearInterval(id);
}, 1000);
medium
A. 1 2 3 (each number printed every second, then stops)
B. 1 2 3 4 5 (prints numbers every second indefinitely)
C. Only 3 printed once after 3 seconds
D. No output because clearInterval is called immediately
Solution
Step 1: Trace the interval execution
Every 1000ms, count increases and prints. When count reaches 3, clearInterval stops it.
Step 2: Understand stopping condition
After printing 3, the interval stops, so no further output.
Final Answer:
1 2 3 (each number printed every second, then stops) -> Option A
Quick Check:
Interval runs 3 times then stops [OK]
Hint: clearInterval inside callback stops after condition [OK]
Common Mistakes:
Assuming it runs forever
Thinking clearInterval stops immediately before first print
Confusing setTimeout with setInterval
4. Identify the error in this code snippet:
const id = setInterval(() => {
console.log('Hello');
});
clearInterval(id);
medium
A. No error, code works fine
B. clearInterval should be called inside the callback
C. setInterval cannot be assigned to a variable
D. Missing interval time argument in setInterval
Solution
Step 1: Check setInterval syntax
setInterval requires two arguments: function and interval time in milliseconds.
Step 2: Analyze the code
Here, the interval time is missing, causing a syntax error or unexpected behavior.
Final Answer:
Missing interval time argument in setInterval -> Option D
Quick Check:
setInterval needs delay argument [OK]
Hint: Always provide delay time in setInterval [OK]
Common Mistakes:
Omitting the delay argument
Calling clearInterval immediately without delay
Thinking setInterval returns undefined
5. You want to print "Tick" every second but stop after 5 ticks. Which code correctly achieves this?
hard
A. setInterval(() => {
console.log('Tick');
clearInterval(timer);
}, 1000);
B. let ticks = 0;
const timer = setInterval(() => {
ticks++;
console.log('Tick');
if (ticks === 5) clearInterval(timer);
}, 1000);
C. let ticks = 0;
setTimeout(() => {
console.log('Tick');
if (ticks < 5) ticks++;
}, 1000);
D. const timer = setInterval(() => {
console.log('Tick');
if (ticks === 5) clearTimeout(timer);
}, 1000);
Solution
Step 1: Identify correct interval and stopping logic
let ticks = 0;
const timer = setInterval(() => {
ticks++;
console.log('Tick');
if (ticks === 5) clearInterval(timer);
}, 1000); uses setInterval with a counter and calls clearInterval after 5 ticks.