简体   繁体   English

将clearInterval应用于间隔后,为什么在调用该间隔时该间隔不再起作用?

[英]After applying clearInterval to an interval why doesn't the interval work again when called?

My game is quite simply you are supposed to click on the start button and move your mouse along the track until you reach the end. 我的游戏非常简单,您应该单击开始按钮,然后沿着轨道移动鼠标直到到达终点。 At the end the timer stops and shows your score. 最后,计时器停止并显示您的得分。 My problem lies with the timer. 我的问题在于计时器。 The timer work perfectly fine the first time but when you click reset to play again it only calls the interval once. 计时器在第一次时可以很好地工作,但是当您单击“重置”以再次播放时,它只会调用间隔一次。 Why? 为什么?

Link to my full code: http://www.codecademy.com/TictacTactic/codebits/AQBK4L/edit 链接到我的完整代码: http : //www.codecademy.com/TictacTactic/codebits/AQBK4L/edit

Thank you in advance! 先感谢您!

JAVA SCRIPT Java脚本

var clicked = false;
var score = 1000;
var timer = setInterval(function(){countDown()}, 250);

$(document).ready(function() {
$('#start').click(function() {
if(!clicked){
    clicked = true;
    countDown();
}
});

$("#lava").mouseover(function(){
if(clicked){
    stopTimer();
    score = 0;
    $("#points").html(score);
}
});

$("#end").mouseover(function(){
if(clicked){
    stopTimer();
    $("#points").html(score);
    clicked = false;
}
});

$('#reset').click(function() {
if(clicked || !clicked){
    clicked = false;
    score = 1000;
    $('#points').html(score);
}
});

});

function countDown() {
score = score - 1;
}

function stopTimer() {
clearInterval(timer);
}

your code var timer = setInterval(function(){countDown()}, 250); 您的代码var timer = setInterval(function(){countDown()}, 250); is at the top and will be executed before the methods are even loaded. 位于顶部,将在方法加载之前执行。 Add at the end of the ready() , look at the bottom: ready()的末尾添加,看一下底部:

var clicked = false;
var score = 1000;
var timer = null;

$(document).ready(function() {
  $('#start').click(function() {

  if(!clicked){
    clicked = true;
    score = 1000;
    timer = setInterval(function(){countDown()}, 250);
    //countDown();
   }
  });

 $("#lava").mouseover(function(){
   if(clicked){
    stopTimer();
    score = 0;
    $("#points").html(score);
   }
 });

 $("#end").mouseover(function(){
   if(clicked){
    stopTimer();
    $("#points").html(score);
    clicked = false;
   }
});

 $('#reset').click(function() {
  if(clicked || !clicked){
    clicked = false;
    score = 1000;
    $('#points').html(score);
  }
});



});

function countDown() {
  score = score - 1;
  $('#points').html(score);
  }

function stopTimer() {
  clearInterval(timer);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM