setTimeout और setInterval
Timers एक delay के बाद या एक interval पर repeatedly code चलाते हैं।
In this page:
Syntax
const timeoutId = setTimeout(callback, milliseconds);
const intervalId = setInterval(callback, milliseconds);
clearTimeout(timeoutId);
clearInterval(intervalId);
setTimeout/setInterval
setTimeout दिए गए milliseconds के कम से कम बाद एक callback एक बार चलाता है और setInterval इसे repeat करता है। दोनों handles return करते हैं जिन्हें आप clearTimeout या clearInterval को pass करते हैं। Timer delays minimums हैं, guarantees नहीं, क्योंकि event loop free होना ज़रूरी है।
Note:
process को exit होने देने के लिए एक timer पर unref() call करें भले ही timer pending हो।
उदाहरण: setTimeout/setInterval
let count = 0;
const id = setInterval(() => {
count += 1;
console.log("tick", count);
if (count === 3) {
clearInterval(id);
console.log("stopped");
}
}, 5);
const t = setTimeout(() => console.log("never runs"), 1000);
clearTimeout(t);
// Output:
// tick 1
// tick 2
// tick 3
// stopped
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- intervals clear करना भूल जाना
- exact timing मान लेना
- एक function की बजाय एक string इस्तेमाल करना
चैप्टर सारांश
- setTimeout एक बार चलता है
- setInterval repeat करता है
- clearTimeout और clearInterval cancel करते हैं
- Delays minimums हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: