0
0
Node.jsframework~5 mins

setInterval and clearInterval in Node.js - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does setInterval do in Node.js?

setInterval runs a function repeatedly at a fixed time interval until stopped.

Click to reveal answer
beginner
How do you stop a repeating action started by setInterval?

You use clearInterval with the interval ID returned by setInterval.

Click to reveal answer
beginner
What type of value does setInterval return?

It returns an interval ID (a number or object) that identifies the timer.

Click to reveal answer
intermediate
Why should you always clear intervals when they are no longer needed?

To avoid memory leaks and unnecessary CPU usage by stopping the repeated function calls.

Click to reveal answer
beginner
Write a simple example of setInterval and clearInterval usage.
<pre>const id = setInterval(() =&gt; {
  console.log('Hello every second');
}, 1000);

setTimeout(() =&gt; {
  clearInterval(id);
  console.log('Stopped interval');
}, 5000);</pre>
Click to reveal answer
What does setInterval return when called?
AAn ID to clear the interval later
BThe result of the function called
CA promise that resolves after the interval
DNothing (undefined)
How do you stop a function from running repeatedly after using setInterval?
ACall <code>clearTimeout</code> with the interval ID
BCall <code>clearInterval</code> with the interval ID
CCall <code>stopInterval</code> with the function name
DSet the interval time to zero
What happens if you never call clearInterval on a running interval?
AThe interval automatically stops after 10 calls
BThe function runs once and stops
CNode.js throws an error
DThe function keeps running forever
Which of these is a correct way to use setInterval?
AsetInterval(() =&gt; console.log('Hi'), 1000);
BsetInterval(console.log('Hi'), 1000);
CsetInterval(console.log, 1000, 'Hi');
DsetInterval('console.log("Hi")', 1000);
What unit is the delay time in setInterval?
AMicroseconds
BSeconds
CMilliseconds
DMinutes
Explain how setInterval and clearInterval work together in Node.js.
Think about starting and stopping a repeating alarm.
You got /3 concepts.
    Describe why it is important to clear intervals when they are no longer needed.
    Imagine leaving a timer running that you don’t need anymore.
    You got /3 concepts.