Skip to content

Commit

Permalink
fix: use batching closer to Marko's for fireEvent
Browse files Browse the repository at this point in the history
  • Loading branch information
DylanPiercey committed Jun 3, 2021
1 parent 970fb11 commit 69c0d99
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,31 @@ function failIfNoWindow() {
}
}

const setImmediate = global.setImmediate || setTimeout;
type Callback = (...args: unknown[]) => void;
const tick =
// Re-implements the same scheduler Marko 4/5 is using internally.
typeof window === "object" && typeof window.postMessage === "function"
? (() => {
let queue: Callback[] = [];
const id = `${Math.random()}`;
window.addEventListener("message", ({ data }) => {
if (data === id) {
const callbacks = queue;
queue = [];
for (const cb of callbacks) {
cb();
}
}
});

return (cb: Callback) => {
if (queue.push(cb) === 1) {
window.postMessage(id, "*");
}
};
})()
: (cb: Callback) => setTimeout(cb, 0);

function waitForBatchedUpdates() {
return new Promise((resolve) => setImmediate(() => setImmediate(resolve)));
return new Promise(tick);
}

0 comments on commit 69c0d99

Please sign in to comment.