zoukankan      html  css  js  c++  java
  • 使用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)
  • 相关阅读:
    F
    Common Subsequence
    Neighbor House
    Robberies(背包)
    Stock Exchange(LIS最长上升子序列问题)
    Compromise(LCS)
    POJ-3356 AGTC (最短编辑距离问题)
    Monkey and Banana(LIS最长上升子序列)
    网络编程之网络协议
    面向对象高级
  • 原文地址:https://www.cnblogs.com/binglove/p/11797275.html
Copyright © 2011-2022 走看看