Last active
November 26, 2018 13:02
-
-
Save AnastasiaDunbar/48489abf1a4a2ebfd146dbcabae79a7e to your computer and use it in GitHub Desktop.
A reference for looping timers.
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
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(); | |
} |
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
🤔