React源码学习:requestIdleCallback

利用浏览器的空闲时间执行任务(P37-P38)
更新于: 2022-06-03 01:07:32

核心价值

利用浏览器的空闲时间执行任务,如果有优先级高的任务执行时,当前任务被终止,执行高级别的任务

基本用法

requestIdleCallback(function(deadline){
// deadline.timeRemaning() 获取浏览器的空余时间(ms)
})

原理<什么是浏览器的空余时间>

  • 1s 执行 60 帧,刚好觉得不卡顿,每一帧的时间在 1000/60 = 16.6ms
  • 当每一帧的执行时间小于16ms,就说明浏览器有空余时间

一个卡顿的任务

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Example RIC</title>
  <style>
    #box {
      background: palevioletred;
      padding: 20px;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
<div id="box">box</div>
<button id="btn1">执行计算任务</button>
<button id="btn2">更改背景颜色</button>
<script>
  var box = document.getElementById('box')
  var btn1 = document.getElementById('btn1')
  var btn2 = document.getElementById('btn2');
  var number = 99999;
  var value = 0;

  function calc() {
    while (number > 0) {
      value = Math.random() < 0.5 ? Math.random() : Math.random()
      console.log(value)
      number--
    }
  }

  btn1.onclick = function () {
    calc()
  }
  btn2.onclick = function () {
    box.style.background = 'green'
  }
</script>
</body>
</html>

用 requestIdleCallback解决这个问题

  • requestIdleCallback(calc) 调用了这个的,优先级偏低的任务
  • 其它事件类任务:优先级高的任务
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Example RIC</title>
  <style>
    #box {
      background: palevioletred;
      padding: 20px;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
<div id="box">box</div>
<button id="btn1">执行计算任务</button>
<button id="btn2">更改背景颜色</button>
<script>
  var box = document.getElementById('box')
  var btn1 = document.getElementById('btn1')
  var btn2 = document.getElementById('btn2');
  var number = 99999;
  var value = 0;

  function calc(deadline) {
    while (number > 0 && deadline.timeRemaining() > 1) {
      value = Math.random() < 0.5 ? Math.random() : Math.random()
      console.log(value)
      number--
    }
    requestIdleCallback(calc)
  }

  btn1.onclick = function () {
    requestIdleCallback(calc)
  }
  btn2.onclick = function () {
    box.style.background = 'green'
  }
</script>
</body>
</html>

参考