← Back to Node.js Course | Chapter 4: Async Programming | Lesson 6 of 7

setTimeout और setInterval

Timers एक delay के बाद या एक interval पर repeatedly code चलाते हैं।

In this page:

  1. setTimeout/setInterval
Syntax
javascript
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

javascript
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. #}
आम गलतियां
  1. intervals clear करना भूल जाना
  2. exact timing मान लेना
  3. एक 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.