倒计时功能是'实际上并没有倒计时

Countdown function isn't actually counting down

本文关键字:倒计时 实际上 并没有 功能      更新时间:2023-09-26
  1. 我在.js文件中有一个函数,它应该显示从10-0开始的倒计时。一旦它达到0,它应该会打开第二个页面。我还没有写它打开页面的部分,但这不是我目前的问题。我的问题是倒计时会显示数字1,而不做其他任何事情。我真的不知道为什么。

  2. 这是的倒计时功能

    function startCountdown() {
        for (var i = 10; i >= 0; i--) { 
            document.getElementById("countdown").value = i;
        }
    }
    
  3. 这是一个称之为的函数

    function startAdPage() {
        setInterval(changeAd(), 2000);
        setInterval(startCountdown(), 1000);
    }
    
  4. 最后,这是它要发送到的HTML代码。一切都是由调用onload方法的body标记启动的。我知道这个部分是有效的,因为我让它做一些其他正常工作的事情。

    <div id="counter">
        <p>The Central Valley Realtors home page will display in 
        <input type="text" value="" class="countdown"/>
        seconds</p>
    </div>
    

setInterval的第一个参数是一个函数。您不是在传递函数,而是在调用函数并传递它返回的任何内容,因为函数名后面有()

此外,您不需要在更新倒计时字段之间等待。Javascript是单线程的,在脚本返回之前页面不会更新。你需要这个:

function startAdPage(){
    var curCounter = 10;
    function startCountdown() {
        document.getElementById("countdown").value = curCounter;
        curCounter--;
        if (curCounter == 0) {
            clearInterval(countdownInterval);
        }
    }
    setInterval(changeAd, 2000);
    var countdownInterval = setInterval(startCountdown, 1000);
}

startCountdown内部的循环一直运行到循环结束,因此值最终为0。此外,您应该在没有参数的情况下将Anonymous函数或未执行的函数传递给setIntervalclearInterval。当您在函数名称的末尾添加()时,您正在执行该函数。将<input type='text' class='countdown' />更改为<input type='text' id='countdown' />,然后尝试以下操作:

function countdown(begin, end, interval, outputElement){
  var repeat = setInterval(function(){
    if(outputElement.innerHTML){
      outputElement.innerHTML = begin--;
    }
    else{
      outputElement.value = begin--;
    }  
    if(begin === end)clearInterval(repeat);
  }, interval);
}
countdown(10, 0, 1000, document.getElementById('countdown'));