Skip to content

React的调度器怎么实现

js
const schduler = (tasks=> {
    const DEFAULT_RUNTIME = 16;
    const { port1port2 } = new MessageChannel();
    
    let sum = 0;
    let isAbort = false;
    
    const promise = new Promise((resolvereject=> {
        // 运行器
        const runner = () => {
            const prevTime = performance.now();
            do {
                if (isAbort) {
                    return reject();
                }
                // 如果任务队列已经空了
                if (tasks.length === 0) {
                    return resolve(sum);
                }
                const task = tasks.shift();
                const value = task();
                sum += value;
            } while (performance.now() - prevTime < DEFAULT_RUNTIME);
            // 当前分片执行完成后开启下一个分片
            port2.postMessage('');
        };
        
        port1.onmessage = function () {
            runner();
        };
        
        port2.postMessage('');
    });
    promise.abort = () => {
        isAbort = true;
    };
    return promise;
};
const schduler = (tasks=> {
    const DEFAULT_RUNTIME = 16;
    const { port1port2 } = new MessageChannel();
    
    let sum = 0;
    let isAbort = false;
    
    const promise = new Promise((resolvereject=> {
        // 运行器
        const runner = () => {
            const prevTime = performance.now();
            do {
                if (isAbort) {
                    return reject();
                }
                // 如果任务队列已经空了
                if (tasks.length === 0) {
                    return resolve(sum);
                }
                const task = tasks.shift();
                const value = task();
                sum += value;
            } while (performance.now() - prevTime < DEFAULT_RUNTIME);
            // 当前分片执行完成后开启下一个分片
            port2.postMessage('');
        };
        
        port1.onmessage = function () {
            runner();
        };
        
        port2.postMessage('');
    });
    promise.abort = () => {
        isAbort = true;
    };
    return promise;
};