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;
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]);
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 }]);
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]);
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]);
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"]);
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"]);
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"]);
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).
I'm here to help with An idle task queue. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.