Ways in Javascript/jQuery/etc to measure time elapsed / trigger events after periods of time

后端 未结 1 992
眼角桃花
眼角桃花 2021-01-25 20:47

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

相关标签:
1条回答
  • 2021-01-25 21:31

    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...
    }
    
    0 讨论(0)
提交回复
热议问题