javascript 计数器脚本未输出任何内容

zaq34kh6  于 2022-12-02  发布在  Java
关注(0)|答案(2)|浏览(140)

我用JavaScript编写了一个计数器代码,并将其输出到我的HTML网页中,但没有打印任何内容。我的逻辑哪里出错了?

<script>
function calCountDown(){
    var temp = new Date("Dec 11, 2022"); //makes an object 'temp' with current date and time
    var deadline = temp.getTime();     //stores the deadline time
    temp= new Date();                   //stores the object of current date and time
    var currentTime = temp.getTime();   //gets the current time

    var timeDifference = deadline - currentTime;

    var day = Math.floor(timeDifference / (1000*60*60*24));       //calculates the difference in days from today till deadline
    var hour = Math.floor((timeDifference % (1000*60*60*24))/(1000*60*60));   //calculates the difference in hours from today till deadline
    var minute = Math.floor((timeDifference % (1000*60*60))/(1000*60));   //calculates the difference in minutes from today till deadline
    var sec = Math.floor((timeDifference % (1000*60))/1000);      //calculates the difference in seconds from today till deadline

    //THIS WILL OUTPUT THE TIME EVERYTIME THIS FUNCTION IS CALLED
    document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

    if(timeDifference < 0){
        clearInterval(x);
        document.getElementById("countdown").innerHTML = "ENDED !!!";
    }
}

 var x = setInterval(calCountDown(), 1000);  

</script>
rdrgkggo

rdrgkggo1#

在这一行中,有两个变量的名称不正确:

document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

我想应该是:

document.getElementById("demo").innerHTML = day + "d " + hour + "h " + minute + "m " + sec + "s ";

此外,deadlinecurrentTIme变量具有相同的值。
我在下面的例子中修改了它,你可以看到它将时间输出到#demo:
第一次

jchrr9hc

jchrr9hc2#

删除setInterval调用中的()

var x = setInterval(calCountDown, 1000);

setInterval本身接受一个函数(或字符串),您传递给它的是来自您的函数的 * 返回值 *,在本例中为undefined
为清楚起见,您执行的是setInterval(undefined, 1000)

更多学习机会

作为一名Web开发人员,我最有用的技能之一是使用浏览器中的JavaScript调试器来单步调试代码、设置断点、检查变量值等。
我建议你开始使用JavaScript debugger来帮助理解你的代码中发生了什么。不仅仅是在这里,任何时候你都不理解代码中发生了什么。每个主流浏览器都有调试器,而不需要任何插件。

相关问题