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)
}
}
 
使用requestAnimationFrame代替setInterval,解决浏览器内存溢出

 

 

let count = 0
function a() {
console.log(count)
count++
}
RAF.setInterval(a, 1000)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-03
  • 2022-01-22
  • 2021-08-25
  • 2022-02-27
  • 2022-02-15
猜你喜欢
  • 2021-11-28
  • 2021-12-05
  • 2021-06-18
  • 2022-01-05
  • 2021-06-07
  • 2021-04-10
  • 2021-07-01
相关资源
相似解决方案