import { onUnmounted } from "vue" // 分帧渲染 export function useDefer(maxCount = 100){ const count = ref(0) let raqId = null function updateFrame(){ count.value++ if(count.value < maxCount){ raqId = requestAnimationFrame(updateFrame) } } updateFrame() onUnmounted(()=>{ cancelAnimationFrame(raqId) }) return function (n){ return count.value >= n } } // 分片渲染(利用浏览器空闲时间执行) // 第一版 function performChunk(datas){ if(datas.length === 0)return let i = 0 function _run(){ if(i>=datas.length)return requestIdleCallback((idle)=>{ while(idle.timeRemaining() > 0 && i<datas.length){ const div = document.createElement('div') div.textContent = datas[i] document.body.appendChild(div) i++ } }) _run() } _run() } // 第二版 // btn.onclick = ()=>{ // const taskHandler = (datas,i)=>{ // const div = document.createElement('div') // div.textContent = datas[i] // document.body.appendChild(div) // } // performChunk(100000,taskHandler) // } // function performChunk(datas,taskHandler){ // if(typeof datas === 'number'){ // datas = {lengths:datas} // } // if(datas.length === 0)return // let i = 0 // function _run(){ // if(i>=datas.length)return // requestIdleCallback((idle)=>{ // while(idle.timeRemaining() > 0 && i<datas.length){ // taskHandler(datas[i],i) // i++ // } // }) // _run() // } // _run() // } // 第三版 btn.onclick = ()=>{ const taskHandler = (datas,i)=>{ const div = document.createElement('div') div.textContent = datas[i] document.body.appendChild(div) } const scheduler = (task)=>{ setTimeout(()=>{ const start = Data.now() task(()=>Date.now() - start<50) },100) } // performChunk(100000,taskHandler,scheduler) browserPerformChunk(100000,taskHandler) } function performChunk(datas,taskHandler,scheduler){ if(typeof datas === 'number'){ datas = {lengths:datas} } if(datas.length === 0)return let i = 0 function _run(){ if(i>=datas.length)return scheduler((isGoOn)=>{ while(isGoOn() > 0 && i<datas.length){ taskHandler(datas[i],i) i++ } }) _run() } _run() } function browserPerformChunk(datas,taskHandler){ const scheduler = (task)=>{ requestIdleCallback((idle)=>{ task(()=>idle.timeRemaining() > 0) }) } performChunk(datas,taskHandler,scheduler) }
标签:function,const,渲染,分片,idle,分帧,return,div,datas From: https://www.cnblogs.com/MDGE/p/18606933