Skip to content

Instantly share code, notes, and snippets.

@AnastasiaDunbar
Last active November 26, 2018 13:02
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 AnastasiaDunbar/48489abf1a4a2ebfd146dbcabae79a7e to your computer and use it in GitHub Desktop.
Save AnastasiaDunbar/48489abf1a4a2ebfd146dbcabae79a7e to your computer and use it in GitHub Desktop.
A reference for looping timers.
function mod(a,b){return((a%b)+b)%b;}
class Timer{
constructor(callback,delay,tickBy=1,...parameters){
this.callback=callback;
this.duration=delay;
this.timer=delay;
this.tickBy=tickBy;
this.parameters=parameters;
}
tick(){
this.timer-=this.tickBy; //Subtract before the if-statement, otherwise `this.timer` would be negative.
if(this.timer<=0){
this.timer+=this.duration+this.tickBy; //`+=` instead of `=` because of decimal values.
this.callback(...this.parameters);
}
}
}
//Usage example:
var myTimer=new Timer(
(...x)=>{say(`Hello ${x.length>1?x.slice(0,-1).join(", ")+" and "+x[x.length-1]:x}!`);}, //Function.
1, //Delay by seconds.
1/60, //Decrementation.
"John","Eric","Larry" //Parameters.
);
function update(){
draw();
myTimer.tick();
}
@AnastasiaDunbar
Copy link
Author

I'm sure that you aren't supposed to read the this.value (also that this is based on setInterval()), since it'd either be jaggy (assigns to 0) or below 0 (subtraction assignment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment