Forked from georgebyte/requestAnimationFrame-throttling.js
Created
August 30, 2019 08:29
-
-
Save mika76/95babed478fe7181bd548f873763e9a7 to your computer and use it in GitHub Desktop.
Javascript: Throttling with 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
// 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