javascript 简单的时钟,从 30 秒开始倒计时,然后执行一个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4435776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:25:52  来源:igfitidea点击:

Simple clock that counts down from 30 seconds and executes a function afterward

javascript

提问by thenengah

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?

我有一个有时间限制的游戏,我需要为用户显示一个倒计时时钟,一旦时间到了,比如 30 秒,就停止游戏。我怎样才能在 javascript 中做到这一点?

回答by casablanca

Use setIntervalto 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:

使用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--;
      }
    }
<div id="some_div">
</div>

回答by praveen-me

You can use setTimeout()function for this like :-

您可以setTimeout()为此使用函数,例如:-

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 1000msfor reducing the time.

在这里,我们使用递归并给它一个setTimeout()of1000ms以减少时间。