Interview question
What is the difference between setTimeout and setInterval, and how do you clear them? setTimeout और setInterval में क्या अंतर है, और उन्हें कैसे clear करें?
Answer
| Function | Behavior | Clear with |
|---|---|---|
| setTimeout | Runs the callback ONCE after the delay | clearTimeout(id) |
| setInterval | Runs the callback REPEATEDLY at the given interval | clearInterval(id) |
// setTimeout - runs once
const timeoutId = setTimeout(() => {
console.log('Runs once after 1 second');
}, 1000);
// Cancelling before it fires
clearTimeout(timeoutId); // callback never runs
// setInterval - runs repeatedly
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Tick ${count}`);
if (count === 5) {
clearInterval(intervalId); // MUST clear manually or it runs forever
}
}, 1000);
// Common bug: forgetting to clear an interval causes it to keep firing
// even after the component/page logic that needed it is gone (memory leak)
function startPolling() {
return setInterval(() => {
console.log('Polling...');
}, 5000);
}
const pollId = startPolling();
// Later, when polling is no longer needed:
clearInterval(pollId);
// setInterval does NOT guarantee exact timing - if the callback takes
// longer than the interval, executions can overlap or queue up
// Modern alternative: recursive setTimeout for more predictable timing
function reliablePoll() {
setTimeout(() => {
console.log('Polling...');
reliablePoll(); // schedules the NEXT call only after this one finishes
}, 5000);
}
reliablePoll(); // avoids overlapping executions that setInterval can cause| Function | व्यवहार | Clear कैसे |
|---|---|---|
| setTimeout | Callback सिर्फ एक बार delay के बाद चलता है | clearTimeout(id) |
| setInterval | Callback बार-बार दिए गए interval पर चलता है | clearInterval(id) |
// setTimeout - एक बार चलता है
const timeoutId = setTimeout(() => {
console.log('1 सेकंड बाद एक बार चलता है');
}, 1000);
// चलने से पहले cancel करना
clearTimeout(timeoutId); // callback कभी नहीं चलता
// setInterval - बार-बार चलता है
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Tick ${count}`);
if (count === 5) {
clearInterval(intervalId); // manually clear करना ज़रूरी
}
}, 1000);
// Common bug: interval clear करना भूलना - memory leak
function startPolling() {
return setInterval(() => {
console.log('Polling...');
}, 5000);
}
const pollId = startPolling();
clearInterval(pollId);
// setInterval exact timing guarantee नहीं देता
// Modern alternative: recursive setTimeout
function reliablePoll() {
setTimeout(() => {
console.log('Polling...');
reliablePoll();
}, 5000);
}
reliablePoll();Was this answer clear?