-
-
Save ncou/bcc912729de0cc5f447c4e78c59e7a87 to your computer and use it in GitHub Desktop.
JavaScript Throttle using requestAnimationFrame
This file contains 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
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