Skip to content

Instantly share code, notes, and snippets.

@julienetie
Last active November 20, 2019 22:23
Show Gist options
  • Select an option

  • Save julienetie/4e61e9164e4fc035b3cf to your computer and use it in GitHub Desktop.

Select an option

Save julienetie/4e61e9164e4fc035b3cf to your computer and use it in GitHub Desktop.
Delay a callback without setTimeout. Make sure to polyfill RAF.
const delay = (callback, duration) => {
let startTime = 0;
let terminate = false;
const raf = requestAnimationFrame;
const loop = (timestamp) => {
startTime = startTime || timestamp;
if (timestamp > startTime + duration && !terminate && callback)
return callback(),terminate = true;
raf(loop);
}
raf(loop);
}
/*
delay(function () {
alert('Hello World');
}, 3000);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment