JavaScript event loop interview questions.
Event loop questions test whether you can predict when code runs, not just what it does. These start with the classic setTimeout versus promise ordering puzzles, move on to await timing and nested callbacks, and end with code you build on top of the loop: drift-free timers, task queues, fake timers for tests and batching within a tick.
2 of these questions have free answers; the rest are in Pro. Updated .
22
questions
- Easy
- 6
- Medium
- 11
- Hard
- 5
What interviewers look for
- You can order synchronous code, microtasks and timers in a snippet, and explain why.
- You know that an async function runs synchronously until its first await.
- You know why a long task or an endless chain of microtasks freezes the page.
- You can split heavy work so the browser can still paint and respond to input.
Concept questions, answered
The definitions and comparisons interviewers open with. Free to read, each with a full answer and examples.
What is the event loop in JavaScript?
The event loop is how JavaScript runs asynchronous code on a single thread. Synchronous code runs on the call stack. When the stack is empty, the engine runs every queued microtask (promise callbacks, await continuations, queueMicrotask), the browser may render a frame, and then the loop takes the next task, such as a timer or a click, and repeats. That order is why a promise callback runs before setTimeout(fn, 0).
What are the call stack and execution context in JavaScript?
An execution context is the record the engine creates to run a piece of code: the global code, or one call of a function. It holds that code's variables, its scope chain and its this. The call stack is the list of active contexts. Calling a function pushes a new context on top, returning pops it, and the engine always runs the context on top.
Synchronous vs asynchronous JavaScript: what is the difference?
Synchronous code runs one statement at a time, and each statement must finish before the next starts, so a slow step blocks everything after it. Asynchronous code starts an operation, such as a network request or a timer, and carries on; the result is handled later by a callback, a promise or await. JavaScript runs your code on a single thread, so asynchronous APIs are how it waits without freezing.
What is a Promise in JavaScript?
A Promise is an object that stands for the eventual result of an asynchronous operation. It starts as pending and settles once, either fulfilled with a value or rejected with a reason. You attach handlers with then, catch and finally, and they run later as microtasks, after the current code has finished.
Async/await vs promises: what is the difference?
async/await is not a separate mechanism. It is syntax built on promises. An async function always returns a promise, and await pauses that function until a promise settles, then gives you its value or throws its error. The same work can be written either way. await mainly reads like synchronous code.
setTimeout vs setImmediate vs process.nextTick
In Node.js, process.nextTick callbacks run as soon as the current operation finishes, before promise callbacks and before the event loop moves on. setImmediate runs in the event loop's check phase, right after I/O polling. setTimeout(fn, 0) runs in the timers phase once at least 1ms has passed. So inside an I/O callback, setImmediate always beats setTimeout(0), and nextTick beats both. Browsers have only setTimeout; setImmediate and nextTick are Node APIs.
What is requestAnimationFrame used for?
requestAnimationFrame(callback) asks the browser to run your function once, just before it paints the next frame. It is used for JavaScript animations, for batching visual updates such as a scroll progress bar, and for throttling work to one run per frame. Because it follows the display's refresh rate and pauses in background tabs, it is smoother and cheaper than animating with setTimeout or setInterval.
What are Web Workers in JavaScript?
A Web Worker is a script that the browser runs on a separate thread, so heavy computation does not block the main thread that handles clicks, scrolling and rendering. The page and the worker cannot share variables or touch each other's objects. They communicate by sending messages with postMessage, which copies the data.
Easy6
- Predict the event-loop order of
setTimeout, promises,queueMicrotaskandawaitFreeInterviewers love this one: read each snippet and write down the exact order of the logs, without running it. Fill in… - Fix the
varloop closure bug three waysThis function should log 0, 1, 2, …, n - 1, but it doesn't: - Implement
clearAllTimeouts()by tracking pending timersBrowsers have no built-in way to cancel every pending timeout. Make one: after your code loads, any timeout created with… - Predict closure results: counters, loops, captured variables and lexical scope"What does this print?" questions about closures appear in almost every JavaScript interview. Read each snippet and…
- Predict the output of loop, timer, promise, hoisting and closure snippetsA JavaScript screening round often ends with a handful of short snippets: "what does this log?" Predict what each one…
- Predict quick-fire results: a detached method, a shadowed
let, a shallowObject.,freeze Promise.andresolve(fn) -0A JavaScript round often opens with short snippets and the question "what does this log?". This set has been reported in…
Medium11
- Build a drift-free
setIntervalon top ofsetTimeoutA countdown built with setTimeout(tick, 1000) after every tick gets slower over time: each tick waits 1000 ms plus… - Implement
LazyMan()with a chainable task queue:eat,sleepandsleepFirstLazyMan is a classic interview question about task queues. The calls in a chain only record what to do; the work runs… - Build Jest-style fake timers with
tick()andrunAll()to test debounce deterministicallyCode built on setTimeout (debounce, throttle, retry with backoff, polling) is slow and flaky to test with real time.… - Fix an IndexedDB transaction that auto-commits during an
await fetch()An offline product catalogue stores products in IndexedDB. This code refreshes prices from the server, and in production… - Build a slideshow where each image has its own duration and a live countdownYou get a list of photos, each with a src and a duration in milliseconds. Build a slideshow that moves to the next photo…
- Build an interval whose delay grows on every run, with a clear functionA reconnect loop should wait 1 s, then 2 s, then 3 s, and stop as soon as the connection is back. setInterval uses one…
- Schedule callbacks with MessageChannel so they run before timersLong work on the main thread blocks clicks and typing. A scheduler breaks it into callbacks and runs them as separate…
- Predict the log order of
awaitinsideforEach,for...of,mapwithPromise., andall reduce"Why does my code continue before the loop is done?" is one of the most common async bugs, and interviewers test it with… - Predict async function timing:
returnversusreturn await, thenables, and extra microtask ticksMost of the time, the exact number of microtask ticks an async function takes does not matter. But it explains real… - Predict nested event loop order: promises that schedule timers, timers that schedule promises, and
awaitin loopsThe basic event-loop question (sync, then microtasks, then timers) has a harder sequel: what happens when callbacks… - Build Vue's update scheduler:
queueJobdedupe, id-sorted flushes, post-flush callbacks andnextTickWhen reactive state changes, Vue does not re-render right away. Each component's update is a job pushed into a queue.…
Hard5
- Implement a Promise library with
.then(),.catch(), chaining, and asynchronous handler schedulingFreeImplement class MyPromise that follows the Promises/A+ rules, without using the built-in Promise anywhere in your… - Build a DataLoader that batches keys requested in the same tick and caches per keyA product page renders 40 review cards, and each card calls getUser(review.authorId). That is 40 requests, many for the…
- Build a time-sliced task runner with priority lanes, cancellation and starvation protectionJavaScript runs on one thread. If you render 5,000 rows or index a large document in one go, the browser cannot handle a…
- Install Jest-style fake timers on the global: patch
setTimeoutandDate,runOnlyPendingTimersand async advancingjest.useFakeTimers() replaces the global timer functions and Date, so code that waits five minutes can be tested in a… - Build a Zone.js-style task tracker: pending macrotasks and microtasks,
isStableandwhenStable()Angular knows when to run change detection, and when a test can safely make assertions, because of Zone.js: it patches…
Practise with tests and full answers.
Every question has a runnable editor, tests and a step-by-step solution. Passes from ₹149, paid once; nothing renews.
Frequently asked
How do I answer 'what is the event loop' in an interview?
Say that JavaScript runs your code on one thread, and the event loop decides what runs next: the current code until the call stack is empty, then every microtask, then possibly a render, then the next task such as a timer or an event. Then walk through a short setTimeout and promise example and its output.
What is the difference between microtasks and macrotasks?
Microtasks are promise callbacks, code after an await, queueMicrotask and MutationObserver callbacks. They all run as soon as the current code finishes. Macrotasks, or tasks, are timers, events and messages, and the loop runs one of them per turn. That is why a promise callback always beats setTimeout with a delay of 0.
Is the event loop the same in Node.js?
The idea is the same and promises still beat timers, but Node.js runs its loop in phases and has process.nextTick and setImmediate. process.nextTick callbacks run before promise callbacks, and setImmediate runs in the check phase after I/O.