Last active
March 5, 2020 09:58
-
-
Save cecigarcia/c692bf893b0cf8b471295cfee5b1945e to your computer and use it in GitHub Desktop.
This file contains 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
const noop = () => {}; | |
const browserSupportsRaf = | |
window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
(window.mozRequestAnimationFrame && window.mozCancelRequestAnimationFrame) || // Firefox 5 ships without cancel support | |
window.oRequestAnimationFrame || | |
window.msRequestAnimationFrame; | |
const requestTimeoutNoRaf = (fn, delay, registerCancel) => { | |
const timeoutId = setTimeout(fn, delay); | |
registerCancel(() => clearTimeout(timeoutId)); | |
} | |
const requestTimeoutRaf = (fn, delay, registerCancel) => { | |
const start = new Date().getTime(); | |
const loop = () => { | |
const delta = new Date().getTime() - start; | |
if (delta >= delay) { | |
fn(); | |
registerCancel(noop); | |
return; | |
} | |
const raf = requestAnimationFrame(loop); | |
registerCancel(() => cancelAnimationFrame(raf)); | |
}; | |
const raf = requestAnimationFrame(loop); | |
registerCancel(() => cancelAnimationFrame(raf)); | |
}; | |
const requestTimeout = browserSupportsRaf ? requestTimeoutRaf : requestTimeoutNoRaf; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment