Skip to content

Instantly share code, notes, and snippets.

@sheniff
Created September 1, 2015 04:15
Show Gist options
  • Select an option

  • Save sheniff/fca5488908b74cb70d60 to your computer and use it in GitHub Desktop.

Select an option

Save sheniff/fca5488908b74cb70d60 to your computer and use it in GitHub Desktop.
Throttled, efficient scroll that only runs once per frame redraw (From MDN documentation https://developer.mozilla.org/en-US/docs/Web/Events/scroll)
;(function() {
var throttle = function(type, name, obj) {
var obj = obj || window;
var running = false;
var func = function() {
if (running) { return; }
running = true;
requestAnimationFrame(function() {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
// Original event is tied to a func that'll only trigger once every animation frame
obj.addEventListener(type, func);
};
/* init - you can init any event */
throttle ("scroll", "optimizedScroll");
})();
// handle event
window.addEventListener("optimizedScroll", function() {
console.log("Resource conscious scroll callback!");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment