Last active
July 9, 2018 10:42
-
-
Save Dobby89/02a28e1d9bcc156398587e1818229dc9 to your computer and use it in GitHub Desktop.
More accurate/consistent interval using requestAnimationFrame
This file contains hidden or 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
/** | |
* 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