The tea shop's pages queue many small jobs: answering a tap on the basket, updating the reviews below the fold, sending analytics. Write createPriorityScheduler(), which returns { postTask }. postTask(callback, options) queues callback and returns a promise that resolves with what it returns, or rejects with what it throws, and an error in one task doesn't stop the others. Follow the ordering of scheduler.postTask() in the Prioritized Task Scheduling spec, but don't use scheduler itself: not every browser has it.
options.priority is "user-blocking", "user-visible" (when it isn't given), or "background". Any other value gives a promise rejected with a TypeError, and nothing is queued. The next task to run is always the oldest waiting task of the highest priority that has any: every user-blocking task before any user-visible one, every user-visible task before any background one, and first in, first out within a priority. A task posted while others run joins the queue and is picked by the same rule.
No callback runs inside postTask. The scheduler starts running tasks in a new task, from a 0 ms setTimeout, and runs one task after another in it. Before each task after the first, if 50 ms or more have passed since that run started, by performance.now(), it yields instead: it stops and carries on in a new task, from another 0 ms setTimeout, so the browser can handle input and paint. When the queues are empty it stops, and a later postTask starts it again. Only one of these timeouts is waiting at a time.
options.signal is an AbortSignal. If it's already aborted, postTask returns a promise rejected with signal.reason, and nothing is queued. If it aborts while the task waits, the task comes out of the queue, never runs, and its promise rejects with signal.reason. An abort after the task has run changes nothing.
const tasks = createPriorityScheduler();
tasks.postTask(() => sendAnalytics(), { priority: "background" });
tasks.postTask(() => renderReviews()); // "user-visible"
const count = await tasks.postTask(() => updateBasket(), { priority: "user-blocking" });
// updateBasket runs first, then renderReviews, then sendAnalytics.
const clock = useFakeTimers({ scheduler: false });
const tasks = createPriorityScheduler();
const order = [];
const post = (name, priority) => tasks.postTask(() => order.push(name), priority && { priority });
post("analytics", "background");
post("reviews");
post("basket", "user-blocking");
post("photos", "user-visible");
post("logs", "background");
post("price", "user-blocking");
await flush();
expect(order).toEqual([]);
await clock.runAllAsync();
expect(order).toEqual(["basket", "price", "reviews", "photos", "analytics", "logs"]);
const clock = useFakeTimers({ scheduler: false });
const tasks = createPriorityScheduler();
const results = [
tasks.postTask(() => 3),
tasks.postTask(() => {
throw new Error("The basket is empty");
}),
tasks.postTask(async () => "saved", { priority: "background" }),
tasks.postTask(() => "after the error"),
].map((promise) => promise.then((value) => "ok: " + value, (error) => "error: " + error.message));
await clock.runAllAsync();
expect(await Promise.all(results)).toEqual(["ok: 3", "error: The basket is empty", "ok: saved", "ok: after the error"]);
const clock = useFakeTimers({ scheduler: false });
const tasks = createPriorityScheduler();
const order = [];
for (const name of ["1", "2", "3", "4", "5"])
tasks.postTask(() => {
order.push("task " + name + " at " + clock.now());
if (name === "3") setTimeout(() => order.push("timer from task 3 at " + clock.now()), 0);
clock.spend(25);
});
setTimeout(() => order.push("timer at " + clock.now()), 0);
await clock.runAllAsync();
expect(order).toEqual([
"task 1 at 0",
"task 2 at 25",
"timer at 50",
"task 3 at 50",
"task 4 at 75",
"timer from task 3 at 100",
"task 5 at 100",
]);
const clock = useFakeTimers({ scheduler: false });
const tasks = createPriorityScheduler();
const order = [];
tasks.postTask(
() => {
order.push("background 1");
tasks.postTask(() => order.push("basket"), { priority: "user-blocking" });
},
{ priority: "background" },
);
tasks.postTask(() => order.push("background 2"), { priority: "background" });
tasks.postTask(() => order.push("reviews"));
await clock.runAllAsync();
expect(order).toEqual(["reviews", "background 1", "basket", "background 2"]);
const clock = useFakeTimers({ scheduler: false });
const tasks = createPriorityScheduler();
const ran = [];
const leaving = new AbortController();
const reason = new Error("The shopper left the page");
const analytics = tasks.postTask(() => ran.push("analytics"), { priority: "background", signal: leaving.signal }).then(() => "ran", (error) => error);
const later = new AbortController();
tasks.postTask(() => {
ran.push("reviews");
later.abort();
});
const photos = tasks.postTask(() => ran.push("photos"), { signal: later.signal }).then(() => "ran", (error) => error.name);
const saving = new AbortController();
const basket = tasks.postTask(() => "basket saved", { priority: "user-blocking", signal: saving.signal });
leaving.abort(reason);
await clock.runAllAsync();
expect(await analytics).toBe(reason);
expect(await photos).toBe("AbortError");
expect(ran).toEqual(["reviews"]);
tasks.postTask(() => ran.push("receipt"), { priority: "user-blocking" });
saving.abort();
await clock.runAllAsync();
expect(await basket).toBe("basket saved");
expect(ran).toEqual(["reviews", "receipt"]);
const clock = useFakeTimers({ scheduler: false });
const tasks = createPriorityScheduler();
const ran = [];
const controller = new AbortController();
controller.abort();
const aborted = tasks.postTask(() => ran.push("aborted"), { signal: controller.signal }).then(() => "ran", (error) => error.name);
const unknown = tasks.postTask(() => ran.push("urgent"), { priority: "urgent" }).then(() => "ran", (error) => error instanceof TypeError);
await clock.runAllAsync();
expect(await aborted).toBe("AbortError");
expect(await unknown).toBe(true);
expect(ran).toEqual([]);
const clock = useFakeTimers({ scheduler: false });
const tasks = createPriorityScheduler();
let timeouts = 0;
const realTimeout = setTimeout;
globalThis.setTimeout = (fn, ms, ...rest) => {
timeouts += 1;
return realTimeout(fn, ms, ...rest);
};
const order = [];
for (const tea of ["green", "mint", "oolong"]) tasks.postTask(() => order.push(tea + " at " + clock.now()));
expect(timeouts).toBe(1);
await clock.runAllAsync();
clock.spend(100);
tasks.postTask(() => order.push("black at " + clock.now()));
await clock.runAllAsync();
expect(order).toEqual(["green at 0", "mint at 0", "oolong at 0", "black at 100"]);
expect(timeouts).toBe(2);
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 A task scheduler with priorities. 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.