[FIX] utils: fix calls to batched callback from within the callback

Previously, calling the batched function from within the callback being
batched would fail as it would be treated as part of the same batch.
This commit fixes that by scheduling the reset of the "called" flag
before calling the callback. This means that all microtasks that were
already in the microtask queue when a batch is about to run are treated
as part of the batch, and all microtasks that will be added by the
callback are not.
This commit is contained in:
Samuel Degueldre
2022-03-29 08:17:47 +02:00
committed by Géry Debongnie
parent 7611ea6033
commit d80fad760c
3 changed files with 66 additions and 4 deletions
+6 -4
View File
@@ -15,11 +15,13 @@ export function batched(callback: Callback): Callback {
await Promise.resolve();
if (!called) {
called = true;
callback();
// 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
await Promise.resolve();
called = false;
// 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();
}
};
}