我有一个给出时间限制的游戏,我需要为用户显示一个倒计时时钟,并在时间结束后停止游戏,例如30秒.我怎么能用javascript做到这一点?
cas*_*nca 19
使用setInterval设置一个计时器.在此计时器中,您可以更新页面中的某些文本,当时间到了,您可以调用所需的任何功能:
var timeLeft = 30;
var elem = document.getElementById('some_div');
var timerId = setInterval(countdown, 1000);
function countdown() {
if (timeLeft == 0) {
clearTimeout(timerId);
doSomething();
} else {
elem.innerHTML = timeLeft + ' seconds remaining';
timeLeft--;
}
}Run Code Online (Sandbox Code Playgroud)
<div id="some_div">
</div>Run Code Online (Sandbox Code Playgroud)