@@ -8,24 +8,33 @@ import {
88import defaults from '../defaults' ;
99import supports from './supported-features' ;
1010
11- let isInsideBatchedSchedule = 0 ;
11+ let batchedScheduled = false ;
12+
13+ let batched = [ ] ;
14+
15+ const executeBatched = ( ) => {
16+ unstable_batchedUpdates ( ( ) => {
17+ while ( batched . length ) {
18+ const currentBatched = batched ;
19+ batched = [ ] ;
20+ currentBatched . forEach ( ( fn ) => fn ( ) ) ;
21+ }
22+ // important to reset it before exiting this function
23+ // as React will dump everything right after
24+ batchedScheduled = false ;
25+ } ) ;
26+ } ;
1227
1328export function batch ( fn ) {
1429 // if we are in node/tests or nested schedule
15- if (
16- ! defaults . batchUpdates ||
17- ! supports . scheduling ( ) ||
18- isInsideBatchedSchedule
19- ) {
30+ if ( ! defaults . batchUpdates || ! supports . scheduling ( ) ) {
2031 return unstable_batchedUpdates ( fn ) ;
2132 }
2233
23- isInsideBatchedSchedule = 0 ;
24- // Use ImmediatePriority as it has -1ms timeout
25- // https://github.com/facebook/react/blob/main/packages/scheduler/src/forks/Scheduler.js#L65
26- return scheduleCallback ( ImmediatePriority , function scheduleBatchedUpdates ( ) {
27- isInsideBatchedSchedule ++ ;
28- unstable_batchedUpdates ( fn ) ;
29- isInsideBatchedSchedule -- ;
30- } ) ;
34+ batched . push ( fn ) ;
35+
36+ if ( ! batchedScheduled ) {
37+ batchedScheduled = true ;
38+ return scheduleCallback ( ImmediatePriority , executeBatched ) ;
39+ }
3140}
0 commit comments