需要检查是否单击了按钮才能继续执行功能

时间:2017-12-01 17:47:38

标签: javascript jquery timer

所以我正在尝试制作一款游戏,其中"开始"点击按钮,定时器关闭,出现额外的按钮,同时更改"开始"按钮进入"暂停"。其中一个按钮是"重启"它会重新启动计时器并带回" start"按钮。如果"重启"在计时器运行时被点击一切顺利。如果"重启"当计时器暂停"时被点击,它会重置时间,但是当游戏开始时#34;再次,基本上两个计时器同时启动。我知道我需要检查"重启"单击按钮然后不启动"开始"功能,但我不知道如何检查。我试过"数据"属性,然后把"开始"函数进入if语句,但函数不起作用。

我的代码在这里 https://jsfiddle.net/peliudzemas/kn3qeuct/1/

$(document).ready(function() {
  $(playButton).on('click', function() {
    displayChange();
    $(time).text(selectedTime + " s");
  });
  startGame();
  restartGame();
});

//Action on "start game" button
//Sets off the timer, adds extra buttons
function startGame() {
  $('.startGame').on('click', function () {
    timerFunction();
    interval1();
    $(this).text("pause the game").css({
      "background-color": "#E05263",
      "color": "white"
    });

    $(this).off('click');
    $(this).removeClass().addClass('pauseGame');
    createButtons();
    pauseGame();
    });
}
//Action on "pause game" button
//Pauses the timer, changes one button
function pauseGame () {
  $('.pauseGame').on('click', function () {
    clearInterval(interval);
    $(this).off('click');
    $(this).removeClass().addClass('resumeGame');
    $(this).text("resume the game").css({
      "background-color": "#73BA9B",
      "color": "white"
    });
    resumeGame();
  });
}

//Action on "resume game" buttons
//Resumes game after it was paused
function resumeGame() {
  $('.resumeGame').on('click', function() {
    interval1();
    $(this).off('click');
    $(this).removeClass().addClass('pauseGame');
    $(this).text("pause the game").css({
      "background-color": "#E05263",
      "color": "white"
    });
    pauseGame();
  });
}

//Action on "restart game" buttons
//Resets and Stops the timer
function restartGame() {
  $(restartButton).on('click', function(){
    $(this).next().removeClass().addClass('startGame');
    $('.startGame').text('start new game').css({
      "background-color": "#73BA9B",
      "color": "white"
    });
    timer = selectedTime;
    $(time).text(selectedTime + " s").css("color", "white");
    clearInterval(interval);
    timerFunction();
    startGame();
  });
}

1 个答案:

答案 0 :(得分:0)

试试这个:

...
// just an interval set to a variable
function interval1 () {
  clearInterval(interval);
  interval = setInterval(timerFunction, 1000);
}
...

JSFidle