用setTimeout實現requestAnimationFrame

需求

請求動畫畫面API兼容到IE10及其以上, 若IE9及其如下瀏覽器需作兼容處理web

這是requestAnimationFrame的pollyfill

function pollyfillRAF (): void {
    const vendors: string [] = ['webkit', 'moz']
    for(let x: number = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
      window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']
      window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']
    }
    if (!window.requestAnimationFrame) { 
      let lastTime: number = 0
      window.requestAnimationFrame = callback => { 
        const currTime: number = new Date().getTime()
        const timeToCall: number = Math.max(0, 16.7 - (currTime - lastTime))
        return window.setTimeout(() => { 
          lastTime = currTime + timeToCall
          callback(lastTime)
        }, timeToCall)
      } 
    } 
    if (!window.cancelAnimationFrame) { 
      window.cancelAnimationFrame = id =>  { clearTimeout(id) } 
    }
  }
複製代碼

重點註釋一下這段優(feng)秀(sao)的代碼

const timeToCall: number = Math.max(0, 16.7 - (currTime - lastTime))
複製代碼

等價於以下的代碼瀏覽器

let timeToCall: number
// 若是間隔超過16.7ms則儘快執行
if (currTime - lastTime >= 16.7) {
    timeTocall = 0
// 不然按間隔的差值補足16.7ms執行
} else {
    timeTocall = 16.7 - (currTime - lastTime))
}
複製代碼
相關文章
相關標籤/搜索