OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 23

Asynchronous JavaScript: Callbacks, setTimeout, and setInterval

By Ratan Updated: 16 Oct 2026

Understand single-threaded execution, event loop, timers, and asynchronous callbacks.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Schedule work without assuming exact timing

JavaScript runs synchronous code to completion on its execution thread. Browser APIs can arrange later callbacks. A timeout delay is an earliest scheduling threshold, not a guarantee that the callback starts at exactly that millisecond.

console.log('A');
setTimeout(() => console.log('B'), 0);
console.log('C');
// A, C, then B

The zero-delay timer cannot interrupt the current synchronous script. Long-running work blocks the main thread and delays timers, rendering and user interaction. Merely putting a long calculation inside setTimeout postpones it; it does not make the calculation nonblocking once it runs.

Start and stop a repeating task

let ticks = 0;
const timer = setInterval(() => {
  ticks += 1;
  console.log('Tick', ticks);
  if (ticks === 3) clearInterval(timer);
}, 1000);

Expect three tick messages before cleanup. Background-tab throttling and other work can delay them. For an elapsed-time display, compute time from an actual timestamp or monotonic clock rather than assuming each tick represents exactly one second.

Async operations inside an interval

setInterval does not wait for an async callback's promise. If a request takes longer than the interval, requests can overlap. A recursive setTimeout scheduled after completion can express a pause between operations, along with cancellation and error handling.

Callbacks and promises

Promise callbacks use the microtask queue, whose ordering differs from ordinary timer tasks. Learn the basic ordering before mixing timers and promises. A synchronous try/catch around registering a timer does not catch an error thrown in the callback later; handle that callback's errors where they occur.

Practice

  1. Cancel a scheduled timeout using its returned timer ID.
  2. Predict A/C/B before running the first example.
  3. Start an interval on a page and stop it when the widget is removed.
  4. Explain why a countdown should compare against a deadline instead of subtracting one blindly on every delayed tick.

हिन्दी संकेत: timer exact घड़ी नहीं है; browser busy होने पर callback देर से चल सकता है।

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat