不卡顿的进度条
实现一个进度条
settimeout
btn3.onclick = function () {
clearTimeout(timer)
progress.style.width = '0'
timer = setTimeout(function fn() {
if (parseInt(progress.style.width) < 500) {
progress.style.width = parseInt(progress.style.width) + 5 + 'px'
progress.innerHTML = parseInt(progress.style.width) / 5 + '%'
timer = setTimeout(fn, 16)
} else {
clearTimeout(timer)
}
}, 0)
}setInterval
btn2.onclick = function () {
clearInterval(timer)
progress.style.width = '0'
timer = setInterval(function () {
if (parseInt(progress.style.width) < 500) {
progress.style.width = parseInt(progress.style.width) + 5 + 'px'
progress.innerHTML = parseInt(progress.style.width) / 5 + '%'
} else {
clearInterval(timer)
}
}, 0)
}requestAnimationFrame 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行
btn1.onclick = function () {
progress.style.width = '0'
const step = () => {
const width = parseInt(progress.style.width)
if (width < 500) {
progress.style.width = width + 5 + 'px'
progress.innerHTML = width / 5 + '%'
console.log('progress.innerHTML', progress.innerHTML)
timer = requestAnimationFrame(step)
} else {
cancelAnimationFrame(timer)
}
}
timer = requestAnimationFrame(step)
}