Last active
November 17, 2020 20:28
-
-
Save cecigarcia/86a85df621e8e32853688f9e7a90d304 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 requestTimeout = (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)); | |
}; | |
let cancel = noop; | |
const registerCancel = fn => cancel = fn; | |
requestTimeout(() => console.log("I'm a delayed work"), 300, registerCancel); | |
// In case I need to cancel the current scheduled work: | |
cancel(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment