美文网首页
setInterval实现

setInterval实现

作者: Chris__Liu | 来源:发表于2019-12-02 16:51 被阅读0次
// setTimeout模拟setInterval
const _setInterval = (fn, t) => {
            function tx() {
                setTimeout(tx, t)
                fn()
            }
            setTimeout(tx, t);
        }
        _setInterval(() => { console.log('2') }, 1000)
// 兼容IE的requestAnimationFrame 
requestAnimationFrame = function (callback) {
      const currTime = new Date().getTime()
      // 为了使setTimteout的尽可能的接近每秒60帧的效果
      const timeToCall = Math.max(0, 16 - (currTime - lastTime))
      const id = window.setTimeout(() => {
        callback(currTime + timeToCall)
      }, timeToCall)
      lastTime = currTime + timeToCall
      return id
    }

相关文章

网友评论

      本文标题:setInterval实现

      本文链接:https://www.haomeiwen.com/subject/bymgwctx.html