WebTech1223411 logo WebTech1223411Web tech, read closely
Browsers

How the Browser Event Loop Decides When Your Code Runs

You set a timeout of zero milliseconds and it still runs after a promise that was created later. A loading spinner never appears because the page freezes before it can paint. A click handler fires half a second late on a mid range phone.

A developer's monitor showing a browser DevTools performance timeline with long task markers above the main thread track

You set a timeout of zero milliseconds and it still runs after a promise that was created later. A loading spinner never appears because the page freezes before it can paint. A click handler fires half a second late on a mid range phone. All three bugs have the same root: the browser event loop, and the order in which it decides what runs next.

Once you understand that order, a whole category of "random" timing bugs becomes predictable. This guide walks through the event loop as browsers actually implement it, with the queues, the rendering step and the practical rules I use when reviewing front-end code.

What the browser event loop is

JavaScript on a web page runs on a single main thread. That thread also handles style calculation, layout and painting for the page. Only one of these things can happen at a time, so the browser needs a scheduler that decides which job goes next. That scheduler is the event loop.

Conceptually, each turn of the loop does three things:

  1. Pick one task from a task queue and run it to completion.
  2. Run every microtask that is waiting, including any new microtasks added along the way.
  3. If it is time to show a new frame, run the rendering steps: requestAnimationFrame callbacks, style, layout and paint.

Then it goes back to step one. The key words are "to completion". Nothing interrupts running JavaScript. If a task takes 300 milliseconds, the page cannot paint, scroll smoothly or respond to clicks for 300 milliseconds.

Tasks, microtasks and rendering in detail

Tasks

Tasks, sometimes called macrotasks, come from things like setTimeout and setInterval callbacks, user input events, network responses, and messages from workers. The browser may keep several task queues and give some, such as input, a higher priority, but each turn still runs just one task.

Microtasks

Microtasks come from promise callbacks (then, catch, finally and the code after an await), queueMicrotask, and MutationObserver. The microtask queue is drained completely after every task. If a microtask queues another microtask, that one runs too, before the browser gets a chance to render.

This explains the classic puzzle. A setTimeout with a delay of 0 queues a task. A resolved promise queues a microtask. The current task finishes, the microtask queue drains, and only then does the next turn pick up the timeout. The promise always wins.

Rendering

Rendering is not done on every turn. Browsers aim to match the display refresh rate, usually 60 frames per second, which gives you roughly 16.7 milliseconds per frame. If nothing changed visually, the browser can skip rendering entirely. When it does render, requestAnimationFrame callbacks run first, then style recalculation and layout, then paint. Heavy layout work here is what we covered in how browser reflow and repaint slow down your page.

Common event loop bugs and how to fix them

SymptomWhat the event loop is doingFix
Spinner never shows before heavy workThe DOM change and the heavy work run in the same task, so no frame is painted between themShow the spinner, then yield before starting the work
Page freezes during a long loopA single task runs for hundreds of millisecondsSplit the work into chunks and yield between them
Recursive promise chain locks the tabMicrotasks keep queueing microtasks, so rendering never gets a turnSchedule each round as a task instead
Animation stuttersUpdates are driven by timers that drift out of sync with framesUse requestAnimationFrame for visual updates

"Yielding" means ending the current task so the loop can render and handle input. The simplest way is to await a promise wrapped around setTimeout with a delay of 0. Chromium based browsers also support scheduler.yield, which resumes your work with a higher priority than other queued tasks so you do not lose your place in line. Feature detect it and fall back to setTimeout elsewhere.

Why "just use async" does not fix a frozen page

A lot of advice says that if code blocks the page, make it async. I see this suggestion in code reviews every few weeks, and it rarely works the way people expect.

Marking a function async does not move it off the main thread. The code inside still runs on the same thread, in the same task, until it reaches an await. And if that await is on an already resolved promise, the continuation becomes a microtask, which still runs before the browser renders. You can write a fully async function that freezes the page just as badly as a synchronous one.

What actually helps is one of three things. Break the work into smaller pieces that each end the task, so rendering and input can happen in between. Move CPU heavy work, such as parsing a large file or image processing, to a Web Worker, which runs on its own thread. Or do less work, which is often the honest answer once you profile it.

Measuring event loop problems in DevTools

You do not need to guess. Open the Performance panel in Chrome or Edge DevTools, enable CPU throttling at 4x to simulate a mid range phone, and record the interaction that feels slow.

  • Long tasks appear with a red triangle in the main thread track. Anything over 50 milliseconds is flagged.
  • Interaction to Next Paint shows in the Interactions track. It measures the time from a click or key press to the next frame, and it is the Core Web Vital most affected by event loop blocking. Aim for under 200 milliseconds.
  • Bottom up view shows which functions take the most time inside a long task.

Firefox's profiler and Safari's Timelines tab show the same information with different labels. Timing can differ between engines, which is one reason a page may feel fine in one browser and sluggish in another, a theme we touched on in why a site works in Chrome but breaks in Safari.

If you want the bigger picture of where this loop sits in the life of a page, our walkthrough of what happens between typing a URL and seeing a page connects the network, parsing and the first run of your scripts.

Frequently asked questions

What is the difference between a task and a microtask?

A task is a unit of work like a timer callback or an input event, and the event loop runs one per turn. Microtasks come mainly from promises and run immediately after the current task finishes, all of them, before the browser renders. That is why promise callbacks run before a zero delay timeout.

Does setTimeout with 0 run immediately?

No. It queues a task that runs on a later turn of the event loop, after the current task and all pending microtasks finish. Browsers also clamp nested timeouts to at least 4 milliseconds after several levels of nesting.

Do Web Workers have their own event loop?

Yes. Each worker runs on its own thread with its own event loop, task queue and microtask queue. Workers cannot touch the DOM, so they suit heavy computation, while the main thread handles rendering and input.

MC
Maren Castellanos

Maren worked in cross-browser QA before editing, and knows the DevTools Network tab better than most people know their inbox. She writes about how browsers load and render pages and about the tools that show what is really happening.

More posts by Maren

More in Browsers

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto