Skip to content

Instantly share code, notes, and snippets.

@ncou
Forked from simmo/throttle.js
Created September 5, 2017 05:33
Show Gist options
  • Save ncou/bcc912729de0cc5f447c4e78c59e7a87 to your computer and use it in GitHub Desktop.
Save ncou/bcc912729de0cc5f447c4e78c59e7a87 to your computer and use it in GitHub Desktop.
JavaScript Throttle using requestAnimationFrame
function throttle(type, name, obj) {
var running = false;
obj = obj || window;
var func = function() {
if (running) return;
running = true;
requestAnimationFrame(function() {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
}
// Usage...
// Throttle scroll event
throttle('scroll', 'scroll.throttled');
// Listen to it
window.addEventListener('scroll.throttled', function() {
console.log('Event fired');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment