分时函数解决一次性加载大量dom造成的卡顿假死

浏览器一次性绘制大量dom会造成卡顿假死

分时函数: 把数据分批绘制; 大任务分成小任务执行;

<body>
        <button onclick="onClick()">click</button>
        <div id="mybox"></div>

</body>
 function onClick() {
            const dom = document.querySelector("#mybox");
           
            const arr = Array.from({ length: 10000 }, (_, i) => i);
            function taskHandle(item) {
                const div = document.createElement('div');
                div.innerText = item;
                dom.appendChild(div);
            }
           
             performChunk(arr, taskHandle)
            // performChunk2(arr, taskHandle, scheduler)
           

        }
 function performChunk(datas, taskHandle) {
            if (datas.length === 0) return;
            let i = 0;
            function _run() {
                window.requestIdleCallback(idle=> {
                    while (idle.timeRemaining()>0 && i < datas.length) {
                        taskHandle(datas[i]);
                        i++;
                    }
                    _run()
                })
            }
            _run()
        }

封装;

//可以传入不同的调用方式;

function scheduler(task) {
                 window.requestIdleCallback((idle) => {
                    task(idle.timeRemaining()>0)
                }, 100)
            }
//or
  function scheduler(task) {
                setTimeout(() => {
                    const start = Date.now();
                    task(() => Date.now() - start < 50)
                }, 100)
            }
// 封装 传入调度;           
 function performChunk2(datas, taskHandle, scheduler) {          
            if (datas.length === 0) return;
            let i = 0;
            function _run() {
                if (i > datas.length) return;
                scheduler((isGoOn)=> {
                    while (isGoOn() && i < datas.length) {
                        taskHandle(datas[i])
                        i++;
                    }
                    _run()
                })
              
            }
            _run()
        }

你可能感兴趣的:(js,javascript,前端,开发语言)