Skip to content

Instantly share code, notes, and snippets.

@kurtextrem
Last active August 30, 2025 10:45
Show Gist options
  • Save kurtextrem/e917f59c8d5268a069bd3f20d2a0d65e to your computer and use it in GitHub Desktop.
Save kurtextrem/e917f59c8d5268a069bd3f20d2a0d65e to your computer and use it in GitHub Desktop.
Scheduling tests
/**
* Queue of functions to invoke
* @type {Array<(time: number) => void>}
*/
let callbacks = [];
let channel = new MessageChannel();
let postMessage = (function() {
this.postMessage(undefined);
}).bind(channel.port2);
// Flush the callback queue when a message is posted to the message channel
channel.port1.onmessage = () => {
// Reset the callback queue to an empty list in case callbacks call
// afterFrame. These nested calls to afterFrame should queue up a new
// callback to be flushed in the following frame and should not impact the
// current queue being flushed
let toFlush = callbacks;
callbacks = [];
let time = performance.now();
for (let i = 0; i < toFlush.length; i++) {
// Call all callbacks with the time the flush began, similar to requestAnimationFrame
// TODO: Error handling?
toFlush[i](time);
}
};
// If the onmessage handler closes over the MessageChannel, the MessageChannel never gets GC'd:
channel = null;
$0.onclick = () => {
long();
scheduler.postTask(() => performance.mark("postTask"), {
priority: "background",
});
requestIdleCallback(() => {
performance.mark("rIC");
requestIdleCallback(() => {
performance.mark("rIC2");
requestIdleCallback(() => performance.mark("rIC3"));
});
scheduler.postTask(() => performance.mark("postTask-bg-in-rIC"), {
priority: "background",
});
scheduler.postTask(() => performance.mark("postTask-visible-in-rIC"), {
priority: "user-visible",
});
scheduler.postTask(() => performance.mark("postTask-blocking-in-rIC"), {
priority: "user-blocking",
});
scheduler.yield().then(() => performance.mark("yield-in-rIC"));
long();
});
requestAnimationFrame(() => {
performance.mark("rAF");
callbacks.push(() => performance.mark("afterFrame-first"))
postMessage()
setTimeout(() => {
performance.mark("setTimeout0");
long();
});
setTimeout(() => performance.mark("setTimeout1"), 1);
requestIdleCallback(() => performance.mark("rIC-in-rAF"));
scheduler.postTask(() => performance.mark("postTask-bg-in-rAF"), {
priority: "background",
});
scheduler.postTask(() => performance.mark("postTask-visible-in-rAF"), {
priority: "user-visible",
});
scheduler.yield().then(() => performance.mark("yield-in-rAF-before-blocking"));
scheduler.postTask(() => performance.mark("postTask-blocking-in-rAF"), {
priority: "user-blocking",
});
scheduler.yield().then(() => performance.mark("yield-in-rAF-after-blocking"));
callbacks.push(() => performance.mark("afterFrame-last"))
postMessage()
});
};
function long() {
const perf = performance.now();
while (true) {
if (performance.now() - perf > 100) break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment