Skip to the code

Yield to the main thread

Long work on the tea shop's pages, like scoring reviews or building the menu, has to stop now and then so the browser can respond to a tap and paint. Write yieldToMain(), which returns a promise that resolves in a new task: await yieldToMain() pauses an async function, lets the browser run whatever is waiting, and carries on after that.

Where the browser has scheduler.yield(), return what it returns, calling it as a method of scheduler (the browser's method throws when this isn't scheduler). Everywhere else, return a promise that a 0 ms setTimeout resolves. Check each time yieldToMain() is called, not once when the script loads, and check for the method, not just the object: some browsers have no scheduler at all, and some have a scheduler with postTask() but no yield().

A promise that's already resolved, like Promise.resolve(), isn't a yield. The code after await runs as a microtask, in the same task, before the browser gets a turn.

async function saveBasket(basket) {
  showSavedBadge(); // painted in the next frame
  await yieldToMain();
  saveToServer(basket); // runs in a task of its own
  sendAnalytics("basket-saved");
}

What the tests check

  1. resolves in a new task, not in a microtask
    const clock = useFakeTimers();
    let resumed = false;
    const waiting = yieldToMain();
    expect(typeof waiting.then).toBe("function");
    waiting.then(() => (resumed = true));
    await flush();
    expect(resumed).toBe(false);
    await clock.runAllAsync();
    expect(resumed).toBe(true);
    
  2. uses scheduler.yield() where the browser has it, and no timeout
    const clock = useFakeTimers();
    const used = { yield: 0, timeout: 0 };
    const realYield = scheduler.yield.bind(scheduler);
    scheduler.yield = () => {
      used.yield += 1;
      return realYield();
    };
    const realTimeout = setTimeout;
    globalThis.setTimeout = (fn, ms, ...rest) => {
      used.timeout += 1;
      return realTimeout(fn, ms, ...rest);
    };
    let resumed = false;
    yieldToMain().then(() => (resumed = true));
    await clock.runAllAsync();
    expect(resumed).toBe(true);
    expect(used).toEqual({ yield: 1, timeout: 0 });
    
  3. calls yield() as a method of scheduler
    const clock = useFakeTimers();
    const realYield = scheduler.yield.bind(scheduler);
    scheduler.yield = function () {
      if (this !== scheduler) throw new TypeError("Illegal invocation");
      return realYield();
    };
    let resumed = false;
    yieldToMain().then(() => (resumed = true));
    await clock.runAllAsync();
    expect(resumed).toBe(true);
    
  4. falls back to a 0 ms timeout where there's no scheduler
    const clock = useFakeTimers({ scheduler: false });
    const delays = [];
    const realTimeout = setTimeout;
    globalThis.setTimeout = (fn, ms, ...rest) => {
      delays.push(Number(ms) || 0);
      return realTimeout(fn, ms, ...rest);
    };
    let resumed = false;
    yieldToMain().then(() => (resumed = true));
    expect(delays).toEqual([0]);
    await flush();
    expect(resumed).toBe(false);
    await clock.runAllAsync();
    expect(resumed).toBe(true);
    
  5. falls back too where scheduler has postTask() but no yield()
    const clock = useFakeTimers();
    globalThis.scheduler = { postTask: scheduler.postTask.bind(scheduler) };
    let timeouts = 0;
    const realTimeout = setTimeout;
    globalThis.setTimeout = (fn, ms, ...rest) => {
      timeouts += 1;
      return realTimeout(fn, ms, ...rest);
    };
    let resumed = false;
    yieldToMain().then(() => (resumed = true));
    await clock.runAllAsync();
    expect(resumed).toBe(true);
    expect(timeouts).toBe(1);
    
  6. checks for scheduler.yield() each time it's called
    const clock = useFakeTimers();
    const installed = globalThis.scheduler;
    let yields = 0;
    const realYield = installed.yield.bind(installed);
    installed.yield = () => {
      yields += 1;
      return realYield();
    };
    globalThis.scheduler = undefined;
    const first = yieldToMain();
    globalThis.scheduler = installed;
    const second = yieldToMain();
    await clock.runAllAsync();
    await Promise.all([first, second]);
    expect(yields).toBe(1);
    
  7. with the timeout, a timer that was already waiting runs before the code after the yield
    const clock = useFakeTimers({ scheduler: false });
    const order = [];
    setTimeout(() => order.push("timer"), 0);
    const work = (async () => {
      order.push("before");
      await yieldToMain();
      order.push("after");
    })();
    await clock.runAllAsync();
    await work;
    expect(order).toEqual(["before", "timer", "after"]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).