Created
March 6, 2017 06:37
-
-
Save georgebyte/dccf6cc62ab3aa55a2f096ef86d9f85d to your computer and use it in GitHub Desktop.
Javascript: Throttling with requestAnimationFrame
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
// Polyfill for rAF | |
window.requestAnimFrame = (function() { | |
return window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
function(callback) { | |
window.setTimeout(callback, 1000 / 60); | |
}; | |
})(); | |
// Throttling function | |
function rafThrottle(fn) { // takes a function as parameter | |
var busy = false; | |
return function() { // returning function (a closure) | |
if (busy) return; // busy? go away! | |
busy = true; // hanging "busy" plate on the door | |
fn.apply(this, arguments); // calling function | |
// using rAF to remove the "busy" plate, when browser is ready | |
requestAnimFrame(function() { | |
busy = false; | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NB: This one doesn't handle trailing event.
If there are two events in short succession that tell about the data change, only the first one will be handled, potentially leaving app in inconsistent state.
To fit the code for such use cases, we have to remember that function was called while
busy
, andfn.apply()
in handler ofrequestAnimationFrame
.Also in 2019 unprefixed support for
requestAnimationFrame
is 96.4%, so most likely there is no more need in a polyfill.