Javascript / jQuery / etc中的方法,用于测量经过一段时间后经过的时间/触发事件 [英] Ways in Javascript/jQuery/etc to measure time elapsed / trigger events after periods of time

查看:331
本文介绍了Javascript / jQuery / etc中的方法,用于测量经过一段时间后经过的时间/触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HTML5(Javascript)制作一个简单的游戏。我想把时间限制在事件上。例如,当玩家进入屋顶正在关闭的房间时,我想给他们一些秒钟来做出决定,然后自动发生其他事件。但是,如果他们做出决定,我根本不想要定时功能。

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 them, I want to give them some seconds to make a decision before automatically having some other event happen. But, if they make a decision, I don't want the timed function to fire at all.

我怎样才能完成这样的事情呢?

How can I accomplish something like this?

推荐答案

为此,我喜欢使用自定义Timer类

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;
            };

您只需创建一个新计时器,将其添加到按固定金额更新的计时器列表中使用主拉环(20ms很好)。因此,如果您的游戏滞后,用户不会受到惩罚;)

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 ;)

例如:
var listOfTimers = [];

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...
}

这篇关于Javascript / jQuery / etc中的方法,用于测量经过一段时间后经过的时间/触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆