Explain the JavaScript event loop, including microtasks and macrotasks.
What the interviewer wants to hear
- JavaScript runs on a single main thread with a call stack
- Async work is handled by browser APIs and queued callbacks
- Microtasks (promises, queueMicrotask) run after each task, fully drained
- Macrotasks (setTimeout, events, I/O) run one per loop turn
- Rendering happens between tasks; long tasks block the UI
Model answer
JavaScript in the browser runs on one main thread with a call stack. When code calls something async, like setTimeout or fetch, the browser handles the waiting and later puts a callback in a queue. The event loop takes one task from the task queue, runs it until the stack is empty, then drains the whole microtask queue, which holds promise callbacks and queueMicrotask callbacks. After that the browser may render a frame, and then it picks the next task. This is why a resolved promise callback runs before a setTimeout of 0. It also means a long synchronous task, or an endless chain of microtasks, blocks rendering and clicks, which hurts INP. I split heavy work into chunks or move it to a Web Worker.
Can you answer it under time pressure?
Take a timed medium round and get scored on every answer.
More medium Frontend Developer questions
- How do you decide where to keep state in a React app: local state, context, a store, or a server-cache library?
- A page has a poor LCP score. How would you investigate and fix it?
- What testing strategy would you use for a frontend application?
- Explain client-side rendering, server-side rendering and static site generation. When would you use each?
- What happens between typing a URL in the browser and seeing the page rendered? Focus on the frontend side.
- A React screen feels slow. How do you find and reduce unnecessary re-renders?
- How do you handle loading, error and empty states when a screen fetches data from an API?
- How do you use TypeScript effectively in a React codebase?
- How would you handle user authentication and tokens in a single-page app or Next.js frontend?