I have a game that gives a time limit and I need to display a countdown clock for the users and stop the game once the time is up such as 30 seconds. How can I do this in javascript?
A countdown timer can be defined as a virtual clock that counts down from a certain date or number to indicate the end or beginning of an offer or event.
Use setInterval
to set up a timer. Within this timer, you can update some text in your page and when the time is up, you can call whatever function you want:
var timeLeft = 30;
var elem = document.getElementById('some_div');
var timerId = setInterval(countdown, 1000);
function countdown() {
if (timeLeft == -1) {
clearTimeout(timerId);
doSomething();
} else {
elem.innerHTML = timeLeft + ' seconds remaining';
timeLeft--;
}
}
<div id="some_div">
</div>
Check out setTimeout
and setInterval
:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With