Skip to content

Instantly share code, notes, and snippets.

@jimmont
Created August 5, 2016 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmont/75328aee73e1067d338a3ee4fb908188 to your computer and use it in GitHub Desktop.
Save jimmont/75328aee73e1067d338a3ee4fb908188 to your computer and use it in GitHub Desktop.
function unthrottle(it){
cancelAnimationFrame(it.index);
it.node.removeEventListener(it.type, it.throttle);
return it;
}
/**
* @param {object} it defines what to throttle, requires 3 properties:
* @param {string} it.type event name
* @param {Node} it.node DOM element
* @param {function} it.handler event-handler attached to node for event
*/
function throttle(it){
it.index = it.time = 0;
it.event = {};
it.relay = function(time){
var _ = it, t = (time - _.time).toFixed(0);
_.time = time;
console.log('relay',_.type,t);
// behave like a standard event-handler
_.handler.call(_.node, _.event);
_.event = {};
};
it.throttle = function _relay(event){
var _ = it;
_.event = event;
cancelAnimationFrame(_.index);
_.index = requestAnimationFrame(_.relay);
};
it.node.addEventListener(it.type, it.throttle);
return it;
}
throttle({type:'scroll', node:window, handler: function(event){
console.log(event.type, event, this);
}});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment