【问题标题】:setting a one minute timer in JavaScript memory aid game在 JavaScript 记忆辅助游戏中设置一分钟计时器
【发布时间】:2014-11-20 19:48:07
【问题描述】:
<div id="counter">1:00</div>
function countdown() {
var secs = 60;
function tick() {
    var counter = document.getElementById("counter");
    secs--;
    counter.innerHTML = "0:" + (secs < 10 ? "0" : "") + String(secs);
    if( secs > 0 ) {
        setTimeout(tick, 1000);
    } else {
        alert("Game Over");
    }
}
tick();
}

countdown(60);

我的这部分游戏有问题。我正在尝试为从 60 开始到 0 结束的游戏设置一个 60 秒计时器,当它到达 0 时游戏停止并且警报显示游戏结束。

我对编程很陌生,所以请尽可能多地给我反馈。我在网上找到了这段代码,大部分我都弄明白了,你能告诉我这里的tick()函数是做什么的吗?

【问题讨论】:

  • “tick() 函数是做什么的” 鉴于代码只不过是tick,那么“我想通了大部分”是什么意思。您具体需要哪些帮助?

标签: javascript function timer counter countdown


【解决方案1】:

这是您可以做到的一种方法:

首先声明一个用于间隔的变量(应该是“全局”,附加到窗口):

var countDownInterval = null;

然后,一个触发滴答间隔的函数,你应该在游戏准备好开始时调用它:

function startCountDown()
{
    countDownInterval = setInterval(tick,1000); //sets an interval with a pointer to the tick function, called every 1000ms
}

每秒调用一次tick函数:

function tick()
{
    // Check to see if the counter has been initialized
    if ( typeof countDownInterval.counter == 'undefined' )
    {
        // It has not... perform the initialization
        countDownInterval.counter = 0; //or 60 and countdown to 0
    }
    else
    {
        countDownInterval.counter++; //or --
    }


    console.log(countDownInterval.counter); //You can always check out your count @ the log console.

    //Update your html/css/images/anything you need to do, e.g. show the count.

    if(60<= countDownInterval.counter) //if limit has been reached
    {
        stopGame(); //function which will clear the interval and do whatever else you need to do.
    }

}

然后是游戏结束后你可以做任何事情的功能:

function stopGame()
{
    clearInterval(countDownInterval);//Stops the interval
    //Then do anything else you want to do, call game over functions, etc.
}

您可以随时致电startCountDown();启动计数器

【讨论】:

    【解决方案2】:

    tick的伪代码:

    function tick() {
       reduce counter variable;
       if counter > 0
          wait for 1 second;  (This is what setTimeout(tick, 1000) means)
          call tick() again (recursively)
       }
       else {
         game over
       }
    }
    

    【讨论】:

      【解决方案3】:

      这样的?

      var countdown = function(sec, tick, done) {
          var interval = setInterval(function(){
              if(sec <= 0) {
                  clearInterval(interval);
                  done();
              } else {
                  tick(sec)
                  sec--;
              }
          }, 1000)
      }
      
      countdown(10, console.log, function(){console.log('done')})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-14
        • 2023-03-31
        相关资源
        最近更新 更多