From 3e9ba9ca8ec064f865f3e75845f6eea05533139a Mon Sep 17 00:00:00 2001 From: Samuel Degueldre Date: Wed, 12 Jul 2023 13:16:23 +0200 Subject: [PATCH] [REF] runtime: simplify implementation of batched Currently the implementation of batched is quite complicated and difficult to read. This is because this approach tried to block all calls at the same point and then only let the first one go through, but an alternative approach is to simply throw away the calls that are made after the first one has been scheduled. This change makes the implementation much simpler to understand. Co-authored-by: Aaron Bohy --- src/runtime/utils.ts | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/src/runtime/utils.ts b/src/runtime/utils.ts index b1c6c92e..143e76d8 100644 --- a/src/runtime/utils.ts +++ b/src/runtime/utils.ts @@ -9,20 +9,13 @@ export type Callback = () => void; * @returns a batched version of the original callback */ export function batched(callback: Callback): Callback { - let called = false; - return async () => { - // This await blocks all calls to the callback here, then releases them sequentially - // in the next microtick. This line decides the granularity of the batch. - await Promise.resolve(); - if (!called) { - called = true; - // wait for all calls in this microtick to fall through before resetting "called" - // so that only the first call to the batched function calls the original callback. - // Schedule this before calling the callback so that calls to the batched function - // within the callback will proceed only after resetting called to false, and have - // a chance to execute the callback again - Promise.resolve().then(() => (called = false)); - callback(); + let scheduled = false; + return async (...args) => { + if (!scheduled) { + scheduled = true; + await Promise.resolve(); + scheduled = false; + callback(...args); } }; }