Skip to content

Instantly share code, notes, and snippets.

@Dobby89
Last active July 9, 2018 10:42
Show Gist options
  • Save Dobby89/02a28e1d9bcc156398587e1818229dc9 to your computer and use it in GitHub Desktop.
Save Dobby89/02a28e1d9bcc156398587e1818229dc9 to your computer and use it in GitHub Desktop.
More accurate/consistent interval using requestAnimationFrame
/**
* A more consistent interval than the native setInterval.
* Should help prevent the time drifting.
*
* @param {function} callback
* @param {integer} delay
*/
const rInterval = function (callback, delay) {
let requestAnimation = window.requestAnimationFrame;
let start = Date.now();
let raf;
const startTime = Date.now();
function intervalFunc(timestamp) {
if (startTime + timestamp - start >= delay) {
start += delay;
callback();
}
raf = requestAnimation(intervalFunc);
}
raf = requestAnimation(intervalFunc);
return {
clear: function() {
cancelAnimationFrame(raf);
}
};
};
/**
* Example usage
*/
const myInterval = rInterval(() => {
// Do something every second
}, 1000);
myinterval.clear(); // Clear interval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment