Performance: setInterval and clearInterval
This affects how often JavaScript code runs repeatedly, impacting CPU usage and event loop responsiveness.
Jump into concepts and practice - no test required
const id = setInterval(() => {
console.log('Running task');
}, 10);
setTimeout(() => {
clearInterval(id);
}, 1000);const id = setInterval(() => {
console.log('Running task');
}, 10);
// never calls clearInterval(id)| Pattern | CPU Usage | Event Loop Blocking | Memory Impact | Verdict |
|---|---|---|---|---|
| setInterval without clearInterval | High (runs forever) | High (blocks event loop) | Medium (keeps references) | [X] Bad |
| setInterval with clearInterval | Low (stops when done) | Low (frees event loop) | Low (clears references) | [OK] Good |
setInterval function do in Node.js?setInterval schedules a function to run repeatedly every specified milliseconds.setTimeout runs once after delay, clearInterval stops intervals.setInterval?clearInterval is the built-in function to stop intervals.clearTimeout stops timeouts, others are invalid functions.let count = 0;
const id = setInterval(() => {
count++;
console.log(count);
if (count === 3) clearInterval(id);
}, 1000);const id = setInterval(() => {
console.log('Hello');
});
clearInterval(id);setInterval requires two arguments: function and interval time in milliseconds.setInterval with a counter and calls clearInterval after 5 ticks.