I\'m trying to make a simple game using HTML5 (Javascript). I want to put time constraints on events. For example, when a player enters a room where the roof is closing in on th
For this, I like to use a custom Timer class
var Timer = function(callback, delay, autoRun){
this.running = (autoRun == undefined)?true:autoRun;
this.completed = false;
this.delay = delay;
this.callback = callback;
};
Timer.prototype.pause = function() {
this.running = false;
return this;
};
Timer.prototype.resume = function() {
this.running = true;
return this;
};
Timer.prototype.finish = function(){
this.running = false;
this.completed = true;
this.callback();
return this;
};
You simply create a new timer, add it to a list of timers that get updated by a fixed amount with your main draw loop (20ms is good). So users don't get penalized if your game is lagging ;)
Ex: var listOfTimers = [];
function draw(){
//Called every frame
for(var i = 0; i<listOfTimers.length; i++){
if(listOfTimers[i].running){
listOfTimers[i].delay -= 20;
if(listOfTimers[i].delay <= 0){
listOfTimers[i].finish();
}
}
//The rest of your draw logic...
}