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

AnastasiaDunbar commented Jun 24, 2018

When this.timer reaches 0, it should not be set to 0 again (which would happen with integers and tick would call callback twice in a row). I find adding if(this.timer<=0){this.timer=this.duration;} after this.timer=mod(this.timer,this.duration); to be ugly, maybe we could use a modulo operation with ceil (so that it won't equal to 0 but this.duration) or a ternary operator?

@AnastasiaDunbar
Copy link
Author

AnastasiaDunbar commented Oct 18, 2018

{
	init:0, //Pay attention to this value.
	value:0,
	FPS:60,
	tick(){
		this.value+=1/this.FPS;
		if(this.value>=this.init){
			call(...);
			this.value-=this.init+(1/this.FPS); //`+(1/this.FPS)`, otherwise `this.value` would still be greater than 0.
		}
	}
}

🤔

@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