如何使用setInterval或setTimeout并在计数期间显示结果? [英] How can I use setInterval or setTimeout and display the results during the count?

查看:164
本文介绍了如何使用setInterval或setTimeout并在计数期间显示结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 setTimeout and setInterval with the same result.

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

我也尝试过使用 .value 代替 .innerHTML ,没有任何帮助。

I also tried using .value in place of .innerHTML with no help.

<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

推荐答案

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/ (包括额外的回调参数)

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

这篇关于如何使用setInterval或setTimeout并在计数期间显示结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆