Skip to main content

JS 实现一个不卡顿的进度条

1.实现一个 0 到 100 的进度条,要求 0 到 100 都要展示,进度条开始执行时,同时有一个计数器开始从 1 开始 步长为 1 的进行累加,一直加到 10000000,要求进度条不会出现卡顿(累加器不影响进度条执行)

<head>
<title>js实现一个不卡顿的进度条</title>
</head>
<style>
.box {
margin-bottom: 100px;
}
</style>
<div class="box">
<div id="progress" style="background-color: lightblue; width: 0; height: 20px; line-height: 20px">
0%
</div>
<div>requestAnimationFrame <button id="btn">run</button></div>
</div>

<script>
let timer;
let i = 0,
max = 20000;
let fnTimer = 0;
let btn = document.getElementById('btn');
let progress = document.getElementById('progress');
btn.onclick = function () {
progress.style.width = '0';
i = 0;
const step = () => {
const width = Number.parseInt(progress.style.width);
if (width < 500) {
progress.style.width = width + 5 + 'px';
progress.innerText = width / 5 + 1 + '%';
console.log('progress.innerHTML', progress.innerHTML);
timer = requestAnimationFrame(step);
} else {
cancelAnimationFrame(step);
}
};
requestAnimationFrame(step);
requestIdleCallback(nonEssentialWork);
};

function add() {
i++;
console.log(i);
}

function nonEssentialWork(idleDeadline) {
console.log('fnIndex', ++fnTimer, idleDeadline.timeRemaining());
while (idleDeadline.timeRemaining() > 0 && i < max) {
add();
}
if (i < max) {
requestIdleCallback(nonEssentialWork);
}
}
</script>