Created
March 9, 2017 21:55
-
-
Save bendc/45690b2e2824f0d4ff9e015439c267da to your computer and use it in GitHub Desktop.
rAF-based random interval
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 randomInterval = (() => { | |
const random = (min, max) => Math.random() * (max - min) + min; | |
return (callback, min, max) => { | |
const time = { | |
start: performance.now(), | |
total: random(min, max) | |
}; | |
const tick = now => { | |
if (time.total <= now - time.start) { | |
time.start = now; | |
time.total = random(min, max); | |
callback(); | |
} | |
requestAnimationFrame(tick); | |
}; | |
requestAnimationFrame(tick); | |
}; | |
})(); | |
randomInterval(() => console.log("hi"), 1000, 2000); // logs "hi" at a random interval between 1 and 2s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
→ Example usage