Skip to content

Instantly share code, notes, and snippets.

@c7x43t
Last active August 10, 2021 11:55
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/d26e4c7212c026e3ab70c9925314535c to your computer and use it in GitHub Desktop.
Save c7x43t/d26e4c7212c026e3ab70c9925314535c to your computer and use it in GitHub Desktop.
var [debounceAnimation,removeDebounceAnimation]=(function(){
var id=1;
var registeredFunctions=new Map();
var registeredFunctionIds=new Map();
var isLooping=false;
function debounceAnimationLoop(){
// iterate over registeredFunctions
var entriesIterator=registeredFunctions.entries();
var entry;
while(!(entry=entriesIterator.next()).done){
entry.value[0](...entry.value[1]);
registeredFunctions.delete(entry.value[0]);
registeredFunctionIds.delete(entry.value[1].id);
}
isLooping=false;
}
function debounceAnimation(func,...args){
var _id=0;
if(!registeredFunctions.has(func)){
registeredFunctions.set(func,args);
registeredFunctionIds.set(args.id,func);
_id=id++;
args.id=_id;
if(!isLooping){ // ensure requestAnimationFrame is called once per frame
isLooping=true;
window.requestAnimationFrame(debounceAnimationLoop);
}
}
return _id;
}
function removeDebounceAnimation(id){
if(id>0&&registeredFunctionIds.has(id)){
var func=registeredFunctionIds.get(id);
registeredFunctionIds.delete(id);
registeredFunctions.delete(func);
}
}
return [debounceAnimation, removeDebounceAnimation];
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment