Skip to content

Instantly share code, notes, and snippets.

@georgebyte
Created March 6, 2017 06:37
Show Gist options
  • Save georgebyte/dccf6cc62ab3aa55a2f096ef86d9f85d to your computer and use it in GitHub Desktop.
Save georgebyte/dccf6cc62ab3aa55a2f096ef86d9f85d to your computer and use it in GitHub Desktop.
Javascript: Throttling with requestAnimationFrame
// 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;
});
};
};
@reverofevil
Copy link

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, and fn.apply() in handler of requestAnimationFrame.

Also in 2019 unprefixed support for requestAnimationFrame is 96.4%, so most likely there is no more need in a polyfill.

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