根據(jù)題意冷溶,如果我們一次性渲染刷新幾萬條數(shù)據(jù)管削,頁面會卡頓蒜哀,因此只能分批渲染彪置,既然知道原理我們就可以使用setInterval和setTimeout拄踪、requestAnimationFrame來實現(xiàn)定時分批渲染,實現(xiàn)每16 ms 刷新一次
requestAnimationFrame跟setTimeout/setInterval差不多拳魁,通過遞歸調(diào)用同一方法來不斷更新畫面以達到動起來的效果惶桐,但它優(yōu)于setTimeout/setInterval的地方在于它是由瀏覽器專門為動畫提供的API,在運行時瀏覽器會自動優(yōu)化方法的調(diào)用,并且如果頁面不是激活狀態(tài)下的話姚糊,動畫會自動暫停贿衍,有效節(jié)省了CPU開銷。
function refresh(total, onceCount) {
//total -> 渲染數(shù)據(jù)總數(shù) onceCount -> 一次渲染條數(shù)
let count = 0, //初始渲染次數(shù)值
loopCount = total / onceCount //渲染次數(shù)
function refreshAnimation() {
/*
* 在此處渲染數(shù)據(jù)
*/
if (count < loopCount) {
count++
requestAnimationFrame(refreshAnimation)
}
}
requestAnimationFrame(refreshAnimation)
}
當(dāng)然也可以使用setTimeout來實現(xiàn):
<!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(() => {
// 插入十萬條數(shù)據(jù)
const total = 100000
// 一次插入 20 條救恨,如果覺得性能不好就減少
const once = 20
// 渲染數(shù)據(jù)總共需要幾次
const loopCount = total / once
let countOfRender = 0
let ul = document.querySelector('ul')
function add() {
// 優(yōu)化性能贸辈,插入不會造成回流
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>