Skip to content

Instantly share code, notes, and snippets.

@simmo
Last active November 9, 2022 10:28
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simmo/34a18a0b98547c16c071 to your computer and use it in GitHub Desktop.
Save simmo/34a18a0b98547c16c071 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