返回列表

requestIdleCallback

默认分类 2021/02/24 06:07

测试了下requestIdleCallback可执行任务数:

'use strict'

var arr = []
var len = 30000
arr.length = len
for (let i = 0; i < len; i++) { arr[i] = 'louis' }

var batch = []

function unImportWork(deadline) {
  while (arr.length > 0) {
    if (deadline.timeRemaining()) {
      arr.splice(parseInt(Math.random() * arr.length), 1)
    } else {
      batch.push(len - arr.length)
      len = arr.length
      break
    }
  }

  if (arr.length > 0) { // 在未来的帧中继续执行
    window.requestIdleCallback(unImportWork)
  } else {
    batch.push(len - arr.length)
    len = arr.length
    window.console.log(batch)
  }
}

window.requestIdleCallback(unImportWork)
// eval(batch.join('+')) 检查总共是不是30000个

输出 [1744, 1851, 1468, 2809, 0, 836, 1770, 1964, 2182, 217, 622, 2604, 1676, 3989, 6268]


>> 留言评论