Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mika76/95babed478fe7181bd548f873763e9a7 to your computer and use it in GitHub Desktop.
Save mika76/95babed478fe7181bd548f873763e9a7 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;
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment