使用requestAnimationFrame
requestAnimationFrame解析
- requestAnimationFram会将一帧的DOM操作保留起来,在一次回流或重绘中完成,并且这个回流和重绘的时间间隔跟随着浏览器的刷新频率,通常是每秒60次。
- 在隐藏或者不可见的元素,就不会进行回流和重绘
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<ul>
控件
</ul>
<script>
setTimeout(() => {
const total = 100000
const once = 20
const loopCount = total / once
let countOfRender = 0
let ul = document.querySelector('ul')
function add() {
const fragment = document.createDocumentFragment()
for (let i = 0; i < once; i++) {
const li = document.createElement('li')
li.innerText = Math.floor(Math.random() * total)
fragment.appendChild(li)
}
ul.appendChild(fragment)
countOfRender += 1
loop()
}
function loop() {
if (countOfRender < loopCount) {
window.requestAnimationFrame(add)
}
}
loop()
}, 0)
</script>
</body>
</html>