JavaScript倒计时不更新

时间:2018-09-02 01:07:39

标签: javascript

我正在为我的网站编写一个重定向页面。在上面,我使用JavaScript倒计时了重定向发生之前的时间。

这是我的HTML代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>We have moved to a new location</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1 style="text-align: center;margin-right: auto; margin-left: auto;font-size: 72px"><b>We have moved to a new location!</b></h1>
<p style="font-size: 36px; text-align: center; margin-right: auto; margin-left:auto;">You will be redirected to our new website in <span id="timer"></span> or you can click <a href="">here</a> to redirect manually.
</body>
<script type="text/javascript">
    $(document).ready(function () {
    document.getElementById('timer').innerHTML = 10;

    function countdown(time) {
        if (time == 0) {
            window.location.href = "http://cs221.cs.usfca.edu/";
        }
        time = time - 1;
        document.getElementById('timer').innerHTML = time;
    }
    setInterval(countdown, 1000, document.getElementById('timer').innerHTML);
})
</script>
</html>

我在这里有一个JSFiddle:https://jsfiddle.net/vhyw57um/13/

我尝试将10插入跨度,但这引起了同样的问题。它将定时器减1,然后陷入循环。我觉得这是一个简单的错误,我只是在这里错过了。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

setInternval的值设置为:

 setInterval(countdown, 1000, 10);

document.getElementById('timer').innerHTML仅被评估一次,而不是每次运行setInterval()都被评估。

换句话说,这不是重新确定document.getElementById('timer')包含的内容。调用该函数时已经执行了该操作。这就是为什么该值只减少到9的原因,因为它总是以10开头。

答案 1 :(得分:0)

请检查我的解决方法:

<script type="text/javascript">
    $(document).ready(function () {
        document.getElementById('timer').innerHTML = 10;
        var time = 10;
        function countdown() {


            if (time == 0) {
                window.location.href = "http://cs221.cs.usfca.edu/";
            }
            time = time - 1;
            document.getElementById('timer').innerHTML = time;
        }
        setInterval(countdown, 1000);
    })
</script>