Skip to content

Instantly share code, notes, and snippets.

@bendc
Created March 9, 2017 21:55
Show Gist options
  • Star 47 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bendc/45690b2e2824f0d4ff9e015439c267da to your computer and use it in GitHub Desktop.
Save bendc/45690b2e2824f0d4ff9e015439c267da to your computer and use it in GitHub Desktop.
rAF-based random interval
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
@bendc
Copy link
Author

bendc commented Mar 9, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment