Last active
September 18, 2019 03:50
-
-
Save gnipbao/626245c59151111737fe6bddb421f516 to your computer and use it in GitHub Desktop.
Drop in replace functions for setTimeout and setInterval that make use of requestAnimationFrame.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(window) { | |
let lastTime = 0, | |
vendors = ['webkit', 'moz'], | |
requestAnimationFrame = window.requestAnimationFrame, | |
cancelAnimationFrame = window.cancelAnimationFrame, | |
i = vendors.length; | |
// try to un-prefix existing raf | |
while (--i >= 0 && !requestAnimationFrame) { | |
requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame']; | |
cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame']; | |
} | |
// polyfill with setTimeout fallback | |
// heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945 | |
if (!requestAnimationFrame || !cancelAnimationFrame) { | |
requestAnimationFrame = function(callback) { | |
var now = +new Date(), | |
nextTime = Math.max(lastTime + 16, now); | |
return setTimeout(function() { | |
callback((lastTime = nextTime)); | |
}, nextTime - now); | |
}; | |
cancelAnimationFrame = clearTimeout; | |
} | |
// export to window | |
window.requestAnimationFrame = requestAnimationFrame; | |
window.cancelAnimationFrame = cancelAnimationFrame; | |
})(window); | |
let __setTimeout = (fn, delay) => { | |
let handler = {}; | |
let now = Date.now, | |
st = now(); | |
let loop = () => { | |
let current = now(), | |
delta = current - st; | |
if (delta >= delay) { | |
fn.call(); | |
cancelAnimationFrame(handler.id); | |
} else { | |
handler.id = requestAnimationFrame(loop); | |
} | |
}; | |
handler.id = requestAnimationFrame(loop); | |
return handler; | |
}; | |
let __setInterval = (fn, delay) => { | |
let handler = {}; | |
let now = Date.now, | |
st = now(); | |
let loop = () => { | |
let current = now(), | |
delta = current - st; | |
if (delta >= delay) { | |
fn.call(); | |
st = now(); | |
} | |
handler.id = requestAnimationFrame(loop); | |
}; | |
handler.id = requestAnimationFrame(loop); | |
return handler; | |
}; | |
let __clearTimeout = (handler) => { | |
let id = handler ? handler.id : null; | |
cancelAnimationFrame(id); | |
}; | |
let __clearInterval = __clearTimeout; | |
export default { | |
setTimeout: __setTimeout, | |
clearTimeout: __clearTimeout, | |
setInterval: __setInterval, | |
clearInterval: __clearInterval | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment