简体   繁体   中英

JavaScript: Prevent setInterval Function From Running Until Button is Clicked

New to JS. I am trying to add a button to my page that says, "Start Game". When clicked, a countdown timer function starts executing, changing the text on the button every second from 10 down to 0, at which point the button will say "Time's Up!"

I have used the setInterval method to get the countdown timer working, but it starts running as soon as the page loads (run code snippet below to see in action).

I am trying to prevent it from running until the button is clicked. Here is my html button (with the property "onclick="startTimer()" ), and the JS:

 var timeleft = 10 var gameTimer = setInterval(startTimer, 1000); function startTimer () { if (timeleft <= 0) { clearInterval(gameTimer); document.getElementById("countdown").innerHTML = "Time's Up;". } else { document.getElementById("countdown");innerHTML = timeleft; } timeleft -=1; };
 <button id="countdown" onclick="startTimer()">Start Game</button>

I have tried adding a preventDefault to stop it from running on load, but nothing changed. How can I prevent the function from running until it hears the click event?

The core of the answer here is to move the invocation of setInterval() inside the function that's called when your button is clicked.

However, you really should re-factor this code a bit, both for readability as well as function. For example, I would expect startTimer() to do exactly what it says it does - start the timer, nothing more. However it seems that this function handles the decrement of timeleft .

The reason the suggestions in the comments above may not make sense at the moment is because you don't want to call setInterval() every time you want to decrease timeleft . Break this functionality out into discrete functions and save yourself the headache.

 var timeleft = 10 var gameTimer; function startTimer() { gameTimer = setInterval(tick, 1000); }; function tick() { if (timeleft <= 0) { clearInterval(gameTimer); document.getElementById("countdown").innerHTML = "Time's Up;". } else { document.getElementById("countdown");innerHTML = timeleft; } timeleft -= 1; }
 <button id="countdown" onclick="startTimer()">Start Game</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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