LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 22 of 25

Event Loop Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Event Loop · Study material

JavaScript runs your code on a single thread, yet it handles timers, clicks and network replies without freezing. The event loop makes that possible: synchronous code runs on the call stack, finished asynchronous work waits in queues, and the loop feeds the next callback in only when the stack is empty. Knowing the rules – sync code first, then every microtask, then one task, then microtasks again – lets you predict the output of any async snippet, which is why "what does this print?" event-loop puzzles appear in almost every JavaScript interview and placement test. After the guide, test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – each one run on Node.js.

The pieces

PartWhat it holdsExamples
Call stackThe functions running right nowyour script, a callback being executed
Web APIs / Node.js APIsWork happening outside JavaScripttimers counting down, network requests, file reads
Task (macrotask) queueCallbacks ready to run, one per loop turnsetTimeout, setInterval, events, I/O, setImmediate
Microtask queueSmall follow-up jobs, all run before the next taskpromise then/catch/finally, await continuations, queueMicrotask, MutationObserver

The order: sync → microtasks → task

The script itself is the first task. When it finishes, the loop empties the microtask queue, then takes one task, then empties the microtask queue again, and so on. That is why a promise callback beats setTimeout(…, 0) even when the timer was scheduled first.

console.log("1. sync – runs on the call stack now");

setTimeout(() => console.log("4. task (macrotask) – a timer callback"), 0);

Promise.resolve().then(() => console.log("3. microtask – a promise callback"));

console.log("2. sync – still the same script");

Output

1. sync – runs on the call stack now
2. sync – still the same script
3. microtask – a promise callback
4. task (macrotask) – a timer callback

Microtasks drain completely

Microtasks added while the queue is being emptied run in the same round – before any task. (This also means an endless chain of microtasks can starve timers and rendering.)

setTimeout(() => console.log("timer"), 0);

Promise.resolve().then(() => {
  console.log("micro 1");
  queueMicrotask(() => console.log("micro 3 – added by micro 1, still before the timer"));
});
queueMicrotask(() => console.log("micro 2"));

Output

micro 1
micro 2
micro 3 – added by micro 1, still before the timer
timer

Microtasks run after every task

It is not "all timers, then all promises": after each single task, its microtasks run before the next task begins.

// After EVERY task the microtask queue is emptied before the next task starts
setTimeout(() => {
  console.log("task 1");
  Promise.resolve().then(() => console.log("  microtask from task 1"));
}, 0);
setTimeout(() => console.log("task 2"), 0);

Output

task 1
  microtask from task 1
task 2

Timers are a minimum delay

setTimeout(fn, ms) means "queue fn after at least ms". Timers fire in order of their due time; equal delays keep the order they were scheduled in. The delay is never a guarantee: the callback waits until the stack is free.

const log = [];
setTimeout(() => log.push("30 ms"), 30);
setTimeout(() => log.push("10 ms"), 10);
setTimeout(() => log.push("20 ms"), 20);
setTimeout(() => log.push("10 ms (second)"), 10);   // same delay → order of scheduling
setTimeout(() => console.log(log), 50);

Output

[ '10 ms', '10 ms (second)', '20 ms', '30 ms' ]

Blocking the thread

While synchronous code runs, nothing else can – not timers, not clicks, not rendering. A long loop makes the page freeze and makes every timer late.

const start = Date.now();
setTimeout(() => {
  const waited = Date.now() - start;
  console.log(`timer asked for 0 ms, ran after ≥ 100 ms: ${waited >= 100}`);
}, 0);

// A long synchronous loop keeps the call stack busy: nothing else can run
while (Date.now() - start < 100) { /* busy for 100 ms */ }
console.log("loop finished");

Output

loop finished
timer asked for 0 ms, ran after ≥ 100 ms: true

async/await in the event loop

An async function runs synchronously up to its first await; everything after it is scheduled as a microtask.

async function task(name) {
  console.log(`${name}: start (sync)`);
  await null;                                   // the rest becomes a microtask
  console.log(`${name}: after await (microtask)`);
}
setTimeout(() => console.log("timeout (task)"), 0);
task("A");
task("B");
console.log("script end");

Output

A: start (sync)
B: start (sync)
script end
A: after await (microtask)
B: after await (microtask)
timeout (task)

Node.js extras

Node.js has the same rules plus two extra queues. process.nextTick callbacks run before promise microtasks; setImmediate runs in the "check" phase, right after I/O callbacks. The loop's phases are: timers → pending callbacks → poll (I/O) → check (setImmediate) → close callbacks, with nextTick and microtask queues emptied between every callback. In the main script the order of setTimeout(fn, 0) and setImmediate is not guaranteed; inside an I/O or timer callback, setImmediate always comes first.

Common mistakes

  • Expecting setTimeout(fn, 0) to run immediately – it waits for the stack and for all microtasks.
  • Reading a value that an async callback has not set yet – the callback runs later.
  • Busy-wait "sleep" loops – they freeze everything; use await with a timer promise.
  • try/catch around setTimeout – it cannot catch errors thrown later in the callback.
  • Passing setTimeout(fn()) – calls fn now and passes its result.
  • Endless microtask loops – starve timers, I/O and rendering.
  • Calling a callback sometimes synchronously, sometimes asynchronously – unpredictable order ("releasing Zalgo").

Key points to remember

  • One thread, one call stack: one piece of JavaScript runs at a time.
  • Sync code → all microtasks → one task → all microtasks → …
  • Promises, await and queueMicrotask are microtasks; timers, events and I/O are tasks.
  • setTimeout's delay is a minimum, not an exact time.
  • Long synchronous work blocks everything – chunk it or move it to a Web Worker.
  • Node.js: nextTick before promises; setImmediate in the check phase.

Frequently asked questions

If JavaScript is single-threaded, who counts the timers?

The browser or Node.js (the host environment). They run timers, network and file work on their own threads and queue your callback when it is ready.

When does the browser repaint the page?

Between tasks, after the microtask queue is empty (usually about 60 times a second). requestAnimationFrame callbacks run just before a repaint.

How do I run heavy work without freezing the page?

Split it into chunks with setTimeout or scheduler APIs, or run it in a Web Worker, which has its own thread and event loop.

Where can I learn more?

Read the event loop, async and await and Promises in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links