使用requestAnimationFrame代替setInterval,解决浏览器内存溢出
1:为什么要写这样的方法,页面需求是需要实时的请求接口,控制组件的位置。当大量组件使用了计时器,会造成网页内存溢出。
const RAF = {
intervalTimer: null,
timeoutTimer: null,
setTimeout (cb, interval) { // 实现setTimeout功能
let now = Date.now
let stime = now()
let etime = stime
let loop = () => {
this.timeoutTimer = requestAnimationFrame(loop)
etime = now()
if (etime - stime >= interval) {
cb()
cancelAnimationFrame(this.timeoutTimer)
}
}
this.timeoutTimer = requestAnimationFrame(loop)
return this.timeoutTimer
},
clearTimeout () {
cancelAnimationFrame(this.timeoutTimer)
},
setInterval (cb, interval) { // 实现setInterval功能
let now = Date.now
let stime = now()
let etime = stime
let loop = () => {
this.intervalTimer = requestAnimationFrame(loop)
etime = now()
if (etime - stime >= interval) {
stime = now()
etime = stime
cb()
}
}
this.intervalTimer = requestAnimationFrame(loop)
return this.intervalTimer
},
clearInterval () {
cancelAnimationFrame(this.intervalTimer)
}
}
let count = 0
function a() {
console.log(count)
count++
}
RAF.setInterval(a, 1000)