javascript 如何使用 setInterval 或 setTimeout 并在计数期间显示结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11075927/
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-26 12:02:06  来源:igfitidea点击:

How can I use setInterval or setTimeout and display the results during the count?

javascript

提问by JonDoeCA

I'm trying to make a timer count down from 5 seconds to zero before a function is called, and I can do that successfully, but I haven't yet been able to display the timer value as it counts down. Instead of displaying the values, the <div></div>goes from a blank space to "Number: 0". I've used both setTimeoutand setIntervalwith the same result.

我试图在调用函数之前让计时器从 5 秒倒计时到零,我可以成功地做到这一点,但我还没有能够在倒计时时显示计时器值。不是显示值,而是<div></div>从空格变为“数字:0”。我已经使用了两者setTimeout并且setInterval结果相同。

<script type="text/javascript">
    for (i = 5; i > 0; i--) {
        function countDown() {
            setInterval(function () {
                document.getElementById("displayDiv").innerHTML = "Number: " + i;
            }, 1000);
        }
    }
</script>

I also tried using .valuein place of .innerHTMLwith no help.

我也尝试.value.innerHTML没有帮助的情况下使用代替。

<input type="button" value="Count" onclick="countDown()" />

<div id="displayDiv" />

This seems like it should be really simple, but it has me stumped. Any help is appreciated

这看起来应该很简单,但它让我难住了。任何帮助表示赞赏

回答by u283863

function countDown(i) {
    var int = setInterval(function () {
        document.getElementById("displayDiv").innerHTML = "Number: " + i;
        i-- || clearInterval(int);  //if i is 0, then stop the interval
    }, 1000);
}
countDown(5);

DEMO: http://jsfiddle.net/DerekL/sFtqZ/(extra callback argument included)

演示:http: //jsfiddle.net/DerekL/sFtqZ/(包括额外的回调参数)

回答by Brett Smith

try

尝试

<script type="text/javascript">
function countDown() {
var i = 5;
var myinterval = setInterval(function() {
    document.getElementById("displayDiv").innerHTML = "Number: " + i;

    if (i === 0) {
        clearInterval(myInterval);
        //call your function
    }
    else {
        i--;
       }
    }, 1000);
}?
</script>

http://jsfiddle.net/pjSKa/

http://jsfiddle.net/pjSKa/