react源码学习之Scheduler

发布时间:2026/6/26 1:33:09

react源码学习之Scheduler 简介Scheduler主要用于调度执行Reconciler组成apiunstable_scheduleCallbackunstable_cancelCallback调度回调有两种方式setTimeout通过MessageChannelTask为任务调度单元type Task{id:number,callback:Callback|null,priorityLevel:PriorityLevel,startTime:number,expirationTime:number,sortIndex:number,isQueued?:boolean,};双堆维护两个最小堆按Task的sortIndex排序taskQueue排序键为expirationTimestartTime小于等于当前时间currentTime的任务放入此堆中timerQueue排序键为startTimestartTime大于当前时间currentTime的任务放入此堆中vartaskQueue:ArrayTask[];vartimerQueue:ArrayTask[];优先级 到超时时间 的映射优先级timeout超时时间ImmediatePriority-1立即超时UserBlockingPriorityconst userBlockingPriorityTimeout 250IdlePrioritymaxSigned31BitInt 1073741823永远不会超时LowPriorityconst lowPriorityTimeout 10000NormalPriorityconst normalPriorityTimeout 5000调度工作循环workLoopfunctionworkLoop(initialTime:number){letcurrentTimeinitialTime;advanceTimers(currentTime);currentTaskpeek(taskQueue);while(currentTask!null){if(!enableAlwaysYieldScheduler){if(currentTask.expirationTimecurrentTimeshouldYieldToHost()){// This currentTask hasnt expired, and weve reached the deadline.break;}}// $FlowFixMe[incompatible-use] found when upgrading FlowconstcallbackcurrentTask.callback;if(typeofcallbackfunction){// $FlowFixMe[incompatible-use] found when upgrading FlowcurrentTask.callbacknull;// $FlowFixMe[incompatible-use] found when upgrading FlowcurrentPriorityLevelcurrentTask.priorityLevel;// $FlowFixMe[incompatible-use] found when upgrading FlowconstdidUserCallbackTimeoutcurrentTask.expirationTimecurrentTime;if(enableProfiling){// $FlowFixMe[incompatible-call] found when upgrading FlowmarkTaskRun(currentTask,currentTime);}constcontinuationCallbackcallback(didUserCallbackTimeout);currentTimegetCurrentTime();if(typeofcontinuationCallbackfunction){// If a continuation is returned, immediately yield to the main thread// regardless of how much time is left in the current time slice.// $FlowFixMe[incompatible-use] found when upgrading FlowcurrentTask.callbackcontinuationCallback;if(enableProfiling){// $FlowFixMe[incompatible-call] found when upgrading FlowmarkTaskYield(currentTask,currentTime);}advanceTimers(currentTime);returntrue;}else{if(enableProfiling){// $FlowFixMe[incompatible-call] found when upgrading FlowmarkTaskCompleted(currentTask,currentTime);// $FlowFixMe[incompatible-use] found when upgrading FlowcurrentTask.isQueuedfalse;}if(currentTaskpeek(taskQueue)){pop(taskQueue);}advanceTimers(currentTime);}}else{pop(taskQueue);}currentTaskpeek(taskQueue);if(enableAlwaysYieldScheduler){if(currentTasknull||currentTask.expirationTimecurrentTime){// This currentTask hasnt expired we yield to the browser task.break;}}}// Return whether theres additional workif(currentTask!null){returntrue;}else{constfirstTimerpeek(timerQueue);if(firstTimer!null){requestHostTimeout(handleTimeout,firstTimer.startTime-currentTime);}returnfalse;}}AI数字营销平台

相关新闻