Skip to content

Commit

Permalink
revamp batching implementation to batch in longer sequences
Browse files Browse the repository at this point in the history
  • Loading branch information
theKashey committed Dec 11, 2023
1 parent 4b0c136 commit e89bef9
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions src/utils/batched-updates.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,33 @@ import {
import defaults from '../defaults';
import supports from './supported-features';

let isInsideBatchedSchedule = 0;
let batchedScheduled = false;

let batched = [];

const executeBatched = () => {
unstable_batchedUpdates(() => {
while (batched.length) {
const currentBatched = batched;
batched = [];
currentBatched.forEach((fn) => fn());
}
// important to reset it before exiting this function
// as React will dump everything right after
batchedScheduled = false;
});
};

export function batch(fn) {
// if we are in node/tests or nested schedule
if (
!defaults.batchUpdates ||
!supports.scheduling() ||
isInsideBatchedSchedule
) {
if (!defaults.batchUpdates || !supports.scheduling()) {
return unstable_batchedUpdates(fn);
}

isInsideBatchedSchedule = 0;
// Use ImmediatePriority as it has -1ms timeout
// https://github.com/facebook/react/blob/main/packages/scheduler/src/forks/Scheduler.js#L65
return scheduleCallback(ImmediatePriority, function scheduleBatchedUpdates() {
isInsideBatchedSchedule++;
unstable_batchedUpdates(fn);
isInsideBatchedSchedule--;
});
batched.push(fn);

if (!batchedScheduled) {
batchedScheduled = true;
return scheduleCallback(ImmediatePriority, executeBatched);
}
}

0 comments on commit e89bef9

Please sign in to comment.