网上看到的文章大多是说原理的,要么就是贴一堆无关紧要的代码,说不到核心上。
Fiber是分片执行,没错,但是怎么把控制权交回UI线程的,
其实是利用了异步原理。
上代码:
1 if ( // If Scheduler runs in a non-DOM environment, it falls back to a naive 2 // implementation using setTimeout. 3 typeof window === 'undefined' || // Check if MessageChannel is supported, too. 4 typeof MessageChannel !== 'function') { 5 6 requestHostCallback = function(cb) { 7 if (_callback !== null) { 8 // Protect against re-entrancy. 9 setTimeout(requestHostCallback, 0, cb); 10 } else { 11 _callback = cb; 12 setTimeout(_flushCallback, 0); 13 } 14 }; 15 16 } else { 17 var channel = new MessageChannel(); 18 var port = channel.port2; 19 channel.port1.onmessage = performWorkUntilDeadline; 20 21 requestHostCallback = function(callback) { 22 scheduledHostCallback = callback; 23 24 if (!isMessageLoopRunning) { 25 isMessageLoopRunning = true; 26 port.postMessage(null); 27 } 28 }; 29 }
如果支持MesasgeChannel 则选择MesasgeChannel, 否则采用setTimeout降级处理。