惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
G
Google Developers Blog
M
MIT News - Artificial intelligence
Vercel News
Vercel News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
GbyAI
GbyAI
B
Blog RSS Feed
Blog — PlanetScale
Blog — PlanetScale
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
The Cloudflare Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Fortinet All Blogs
L
LangChain Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
About on SuperTechFans
T
The Blog of Author Tim Ferriss
B
Blog
J
Java Code Geeks
Hugging Face - Blog
Hugging Face - Blog
I
InfoQ
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The Scheduling Boundaries Behind Responsive UI
Marsha Teo · 2026-05-18 · via DEV Community

This is the last article in a series on how JavaScript actually runs. You can read the full series here or on my website.


We now know how the event loop and rendering pipeline behave.

The browser:

  • Runs a macrotask to completion.
  • Drains all microtasks.
  • Executes any scheduled requestAnimationFrame callbacks.
  • Drains all microtasks.
  • Performs layout and paint to produce the next frame.
  • Moves on to the next macrotask.

Given that environment, how should we write UI code?


Long Tasks Block Everything

If you want the UI to stay responsive, your tasks must yield quickly.

Consider this:

button.addEventListener("click", () => {
  const start = performance.now();

  while (performance.now() - start < 3000) {
    // busy loop for 3 seconds
  }

  console.log("done");
});

Enter fullscreen mode Exit fullscreen mode

Once the button is clicked, the page becomes unresponsive. The click handler is a macrotask and nothing can interrupt it. Everything else has to wait: there is no re-rendering, no new input, no requestAnimationFrame callbacks.

Long-running tasks monopolize the main thread. While they run, rendering pauses, input waits, animations stall and timers are delayed. Responsive UI depends on cooperation.


Microtasks Do Not Yield to Rendering

Chaining promises look like a way to break work into pieces:

button.addEventListener("click", () => {
  Promise.resolve()
    .then(() => heavyWork())
    .then(() => {
      status.textContent = "Halfway...";
    })
    .then(() => moreHeavyWork())
    .then(() => {
      status.textContent = "Done";
    });
});

Enter fullscreen mode Exit fullscreen mode

However, each .then() callback becomes a microtask when its associated Promise resolves. Because the browser must drain the entire microtask queue before rendering, chaining Promises does not create render opportunities. As a result, the user sees nothing until "Done" shows up on screen.

If you want to let the browser render, you must introduce a scheduling boundary:

button.addEventListener("click", () => {
  Promise.resolve()
    .then(() => heavyWork())
    .then(() => {
      status.textContent = "Halfway...";

      return new Promise(resolve => {
        // setTimeout used to introduce a scheduling boundary
        setTimeout(resolve, 0); 
      });
    })
    .then(() => heavyWork())
    .then(() => {
      status.textContent = "Done";
    });
});

Enter fullscreen mode Exit fullscreen mode

Alternatively, we can consider:

button.addEventListener("click", () => {
  Promise.resolve()
    .then(() => heavyWork()
    .then(() => {
      status.textContent = "Halfway...";

      return new Promise(resolve => {
        // requestAnimationFrame used to introduce a scheduling boundary
        requestAnimationFrame(resolve); 
      });
    })
    .then(() => heavyWork()
    .then(() => {
      status.textContent = "Done";
    });
});

Enter fullscreen mode Exit fullscreen mode

Both approaches work because a .then() callback is only queued once its associated Promise resolves. By returning a Promise that resolves later, we delay when the next microtask is created. setTimeout yields to the next macrotask, while requestAnimationFrame yields to the next frame.


Choosing Between Promises, setTimeout and requestAnimationFrame

These mechanisms signal different intentions to the browser. They are not interchangeable.

Use a Promise when you need to continue work immediately after the current macrotask completes, but before the browser moves on. They are ideal for continuing work that logically depends on previous work. They help to preserve order, transform results and update state after completion. They are not a yielding mechanism.

Use setTimeout when you need to create a real scheduling gap. They are useful for breaking up long computation, deferring non-critical work and yielding cooperatively. They are general purpose yields.

Use requestAnimationFrame when you are performing visual updates. It is ideal for animations and layout-sensitive work.

Decision tree to decide among Promises, setTimeout and requestAnimationFrame


Different scheduling APIs solve different coordination problems in the browser event loop.

Align Visual Updates to Frames

Consider this approach:

document.addEventListener("mousemove", (event) => {
  box.style.left = event.clientX + "px";
});

Enter fullscreen mode Exit fullscreen mode

If the mouse fires 200 events per second, this code attempts 200 DOM updates per second. But on most displays, the refresh happens about 60 times per second. Visual work that exceeds that rate is simply wasted.

Instead, consider:

let latestX = 0;
let scheduled = false;

document.addEventListener("mousemove", (event) => {
  latestX = event.clientX;

  if (!scheduled) {
    scheduled = true;

    requestAnimationFrame(() => {
      box.style.left = latestX + "px";
      scheduled = false;
    });
  }
});

Enter fullscreen mode Exit fullscreen mode

We use requestAnimationFrame to update at most once per frame, no matter the rate at which input can fire.


Respect the Frame Budget

requestAnimationFrame guarantees alignment to the frames but it does not guarantee smoothness. On a 60fps display, the browser has roughly 16ms per frames. That 16ms must include all JavaScript and rendering work.

If the JavaScript executed alone takes longer than that, the browser cannot complete rendering in time:

requestAnimationFrame(() => {
  const start = performance.now();

  while (performance.now() - start < 40) {
    // 40ms of work
  }
});

Enter fullscreen mode Exit fullscreen mode

This callback runs before the browser renders but it blocks for 40ms and therefore exceeds the frame budget. Since the browser cannot display partial frames, if the 16ms window is missed, that frame is dropped. Instead of rendering at 60 frames per second, the browser renders less frequently: Animations can appear jerky, motion uneven and interactions delayed.

So while requestAnimationFrame helped with alignment, we must still finish the frame work within the frame window. Either work fits inside the budget or it is spread across multiple frames. For instance, this could mean animating in steps or deferring non-critical computation.

Responsive UI requires both correct scheduling and work that fits inside the budget.


Guard Against Stale Asynchronous Work

Asynchronous code creates delays. During this window, state can change:

function loadData() {
  fetch("/data")
    .then(response => response.json())
    .then(data => {
      render(data);
    });
}

Enter fullscreen mode Exit fullscreen mode

This looks harmless but imagine the user clicking twice quickly and loadData() is called twice in succession. If the second request finishes first, the first request would render stale data and the UI would then be incorrect.

One common pattern is to guard against outdated work:

let currentRequestId = 0;

function loadData() {
  const id = ++currentRequestId;

  fetch("/data")
    .then(response => response.json())
    .then(data => {
      if (id !== currentRequestId) return;
      render(data);
    });
}

Enter fullscreen mode Exit fullscreen mode

Now each request captures its own response and only the most recent request is allowed to update the UI.


Designing With the Browser, Not Against It

Responsive UI emerges from working within the browser's execution model.

In practice, that often means:

  • Keeping tasks short so the browser can continue scheduling
  • Remembering that microtasks do not yield to rendering
  • Aligning visual updates to frame boundaries
  • Ensuring that work fits within the frame budget.
  • Verifying that delayed work is still relevant before applying it

I started this series because I had code that used Promises, setTimeout, and requestAnimationFrame. They all felt “asynchronous” and interchangeable. Turns out they weren't.

Good UI code knows which scheduling boundary to use and when.


This article was originally published on my website.