Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the difference between setTimeout and setInterval, and how do you clear them? setTimeout और setInterval में क्या अंतर है, और उन्हें कैसे clear करें?

Answer
FunctionBehaviorClear with
setTimeoutRuns the callback ONCE after the delayclearTimeout(id)
setIntervalRuns the callback REPEATEDLY at the given intervalclearInterval(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 कैसे
setTimeoutCallback सिर्फ एक बार delay के बाद चलता हैclearTimeout(id)
setIntervalCallback बार-बार दिए गए 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?