请求动画画面API兼容到IE10及其以上, 若IE9及其如下浏览器需作兼容处理web
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) }
}
}
复制代码
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))
}
复制代码