Skip to content

Instantly share code, notes, and snippets.

@c7x43t
Last active August 30, 2021 19:10
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 c7x43t/b4121fde01906ee5156bb373ebb02b24 to your computer and use it in GitHub Desktop.
Save c7x43t/b4121fde01906ee5156bb373ebb02b24 to your computer and use it in GitHub Desktop.
// throttle a function with requestanimationFrame
// throttledFunction = throttleAnimationFrame(func, immediate=false)
// which problem is solved? If you have a frequent event source you need to react
// to with a possible rerender of view components, then the function need to be executed
// with the next render frame but no more than once per render frame to save cpu cycles
// example:
// document.addEventListener('scroll',throttleAnimationFrame(eventHandler)) // will trigger at most once every render frame
var throttleAnimationFrame = (function(){
var stack=new Map();
var called=new Map();
function requestAnimationFrameLoop(){
called.clear();
var keys=stack.keys();
// execute all functions in stack
for(var func of stack.keys()){
if(!called.has(func)){
stack.get(func)();
called.set(func,true);
stack.delete(func);
}
}
window.requestAnimationFrame(requestAnimationFrameLoop);
}
window.requestAnimationFrame(requestAnimationFrameLoop);
return function throttleAnimationFrame(func, immediate){
return function() {
var context = this, args = arguments;
if(immediate && !called.has(func)){
func.apply(context,args);
called.set(func,true);
}else if(!stack.has(func)){
stack.set(func,func.bind(context,...args));
}
};
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment