问题
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