Simple clock that counts down from 30 seconds and executes a function afterward [closed]
开发者_如何学编程
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Improve this questionOriginal close reason(s) were not resolved
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?
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/
You can use setTimeout()
function for this like :-
let timeElm = document.getElementById('timeElm');
let timer = function(x) {
if(x === 0) {
return;
}
timeElm.innerHTML = x;
return setTimeout(() => {timer(--x)}, 1000)
}
timer(30);
In this, we use recursion and gave it a setTimeout()
of 1000ms
for reducing the time.
精彩评论