Skip to the code

An idle task queue

The tea shop saves recently viewed teas, warms caches, and sends analytics, and none of it is urgent. Write createIdleQueue(options), which returns { push }. push(task) adds a function to the queue and returns a promise that resolves with what the task returns, or rejects with what it throws. Tasks run in the order they were pushed, and only inside requestIdleCallback callbacks. An error in one task rejects its own promise and doesn't stop the others.

Ask for one idle callback at a time, and only when there's a task waiting, with { timeout: options.timeout } (1000 when it isn't given). In the callback, run the next task while deadline.timeRemaining() is more than options.margin ms (0 when it isn't given), checking before every task. When the time runs out with tasks left, ask for another idle callback for the rest. A callback asked for from inside an idle callback runs in a later idle period, never the current one, as the requestIdleCallback spec says.

A page that's never idle still runs the callback once its timeout has passed, with deadline.didTimeout true and no time remaining. Then run the first task anyway, and only that one, so the queue keeps moving, one task per timeout, without turning into a long task on a page that's already busy.

const later = createIdleQueue();
later.push(() => localStorage.setItem("recent", JSON.stringify(recentTeas)));
const sent = later.push(() => sendAnalytics("menu-viewed"));
// Both run when the browser is idle, or one per second on a busy page.
await sent;

What the tests check

  1. runs nothing right away, then runs the tasks in order and resolves each push
    const clock = useFakeTimers();
    const queue = createIdleQueue();
    const ran = [];
    const results = ["green", "mint", "oolong"].map((tea) =>
      queue.push(() => {
        ran.push(tea);
        return tea.length;
      }),
    );
    expect(ran).toEqual([]);
    await clock.runAllAsync();
    expect(ran).toEqual(["green", "mint", "oolong"]);
    expect(await Promise.all(results)).toEqual([5, 4, 6]);
    
  2. asks for one idle callback, with a 1000 ms timeout, once there's a task, and runs the tasks inside it
    const clock = useFakeTimers();
    const asked = [];
    let inside = false;
    const realIdle = requestIdleCallback;
    globalThis.requestIdleCallback = (callback, options) => {
      asked.push(options);
      return realIdle((deadline) => {
        inside = true;
        callback(deadline);
        inside = false;
      }, options);
    };
    const queue = createIdleQueue();
    expect(asked).toEqual([]);
    const where = [];
    for (const tea of ["green", "mint", "oolong"]) queue.push(() => where.push(tea + (inside ? " in an idle callback" : " elsewhere")));
    expect(asked).toEqual([{ timeout: 1000 }]);
    await clock.runAllAsync();
    expect(where).toEqual(["green in an idle callback", "mint in an idle callback", "oolong in an idle callback"]);
    expect(asked).toEqual([{ timeout: 1000 }]);
    
  3. stops when the idle period runs out, and carries on in the next one
    const clock = useFakeTimers();
    let period = 0;
    const realIdle = requestIdleCallback;
    globalThis.requestIdleCallback = (callback, options) =>
      realIdle((deadline) => {
        period += 1;
        callback(deadline);
      }, options);
    const queue = createIdleQueue();
    const periods = [];
    for (let index = 0; index < 12; index++)
      queue.push(() => {
        clock.spend(10);
        periods.push(period);
      });
    await clock.runAllAsync();
    // Each idle period here is 50 ms: five 10 ms tasks fit in one.
    expect(periods).toEqual([1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3]);
    
  4. starts a task only while more than the margin remains
    const clock = useFakeTimers();
    let period = 0;
    const realIdle = requestIdleCallback;
    globalThis.requestIdleCallback = (callback, options) =>
      realIdle((deadline) => {
        period += 1;
        callback(deadline);
      }, options);
    const queue = createIdleQueue({ margin: 10 });
    const periods = [];
    for (let index = 0; index < 8; index++)
      queue.push(() => {
        clock.spend(10);
        periods.push(period);
      });
    await clock.runAllAsync();
    // With 10 ms left, the fifth task waits: 10 isn't more than the margin.
    expect(periods).toEqual([1, 1, 1, 1, 2, 2, 2, 2]);
    
  5. a page that's never idle still runs one task each time the timeout passes
    const clock = useFakeTimers();
    clock.idleBudget = 0;
    const queue = createIdleQueue({ timeout: 500 });
    const times = [];
    for (const tea of ["green", "mint", "oolong"]) queue.push(() => times.push(tea + " at " + clock.now()));
    await clock.runAllAsync();
    expect(times).toEqual(["green at 500", "mint at 1000", "oolong at 1500"]);
    
  6. an error rejects its task's promise, and the queue goes on
    const clock = useFakeTimers();
    const queue = createIdleQueue();
    const outcomes = [
      queue.push(() => "saved green"),
      queue.push(() => {
        throw new Error("Storage is full");
      }),
      queue.push(() => "saved mint"),
    ].map((promise) => promise.then((value) => "ok: " + value, (error) => "error: " + error.message));
    await clock.runAllAsync();
    expect(await Promise.all(outcomes)).toEqual(["ok: saved green", "error: Storage is full", "ok: saved mint"]);
    
  7. a task pushed after the queue has emptied asks for a new idle callback
    const clock = useFakeTimers();
    const queue = createIdleQueue();
    const ran = [];
    queue.push(() => ran.push("green"));
    await clock.runAllAsync();
    clock.spend(200);
    queue.push(() => ran.push("mint at " + clock.now()));
    await clock.runAllAsync();
    expect(ran).toEqual(["green", "mint at 202"]);
    

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).