Last active
August 30, 2021 19:10
-
-
Save c7x43t/b4121fde01906ee5156bb373ebb02b24 to your computer and use it in GitHub Desktop.
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
// 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