本文介绍了游戏计时器Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个倒数计时器.如果秒等于零,则将2 secs设置为var seconds.请帮忙.我需要等待2秒后停止程序循环

I'm creating a countdown timer. If seconds is equal to zero I have set 2 secs to var seconds. Please help. I need to stop the program from looping after getting the 2 seconds

var isWaiting = false;
var isRunning = false;
var seconds = 10;
function GameTimer(){
     var minutes = Math.round((seconds - 30)/60);
     var remainingSeconds = seconds % 60;
     if(remainingSeconds < 10){
           remainingSeconds = "0" + remainingSeconds;
     }
     document.getElementById('waiting_time').innerHTML = minutes + ":" + remainingSeconds;
     if(seconds == 0){
          isRunning = true;
          seconds += 2; //I need to stop the program from looping after getting the 2 seconds

     }else{
          isWaiting = true;
          seconds--;
     }
}
var countdownTimer = setInterval(GameTimer(),1000);

推荐答案

这是您的固定代码:

var isWaiting = false;
var isRunning = false;
var seconds = 10;
var countdownTimer;
var finalCountdown = false;

function GameTimer() {
    var minutes = Math.round((seconds - 30) / 60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds;
    }
    document.getElementById('waiting_time').innerHTML = minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        isRunning = true;
        seconds += 2;

        if (finalCountdown) {
            clearInterval(countdownTimer); // Clear the interval to stop the loop
        } else {
            finalCountdown = true; // This will allow the 2 additional seconds only once.
        }

    } else {
        isWaiting = true;
        seconds--;
    }
}
countdownTimer = setInterval(GameTimer, 1000); // Pass function reference, don't invoke it.

工作演示: http://jsfiddle.net/nEjL4/1/

这篇关于游戏计时器Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 05:53