Simple Interval Not Clearing

无人久伴 提交于 2019-12-26 02:37:42

问题


I am building a game program with the following prompt:

"Modify Challenge #3 so that every time a player clicks the heading, instead of stopping, the heading speeds up, making it harder and harder to click. Keep track of the number of times the heading has been clicked and update the heading text so it shows this number. When the player has reached 10 clicks, stop the animation and change the text of the heading to “You Win.” Hint: To speed up, you’ll have to cancel the current interval and then start a new one with a shorter interval time."

Here is the click event itself. I have everything down except the text won't stop when there are more than 10 clicks. I have linked my jfiddle as well.

$("#heading").click(function() {
       clearInterval(move);
       if (clicks < 10)
       {
            var move = setInterval(moveHeading, speed -= 2);
            $("#heading").html(clicks + " Clicks!");
            clicks++;
       } 
       else 
       {
            $("#heading").html("You won!");
            $("#heading").css("color","red");
            clearInterval(move);
       }
 });

https://jsfiddle.net/jggzb49j/1/


回答1:


declare variable move outside instead of the inside handler function

var move;
$("#heading").click(function() {
  clearInterval(move);
  if (clicks < 10) {
    move = setInterval(moveHeading, speed -= 2);
    $("#heading").html(clicks + " Clicks!");
    clicks++;
  } else {
    $("#heading").html("You won!");
    $("#heading").css("color", "red");
    clearInterval(move);
  }
});


来源:https://stackoverflow.com/questions/43109051/simple-interval-not-clearing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!