JS拒绝循环函数

时间:2016-01-28 10:52:48

标签: javascript loops countdown

我在倒计时时出现问题。我已经进行了倒计时,但JS更改HTML拒绝循环。我有一个 setInterval ,我已经尝试过,而且做了循环但没有工作。我真的很感激一些帮助。

HTML:

<body>
    <center>
    <h1> Input the date and time you want to countdown to!</h1>
    <form>
        Second:<input id="seconds" type="number"><br>
        Minute:<input id="minutes" type="number"><br>
        Hour:<input id="hours" type="number"><br>
        Day:<input id="days" type="number"><br>
        Month:<input id="months" type="text"><br>
        Year:<input id="years" type="number"><br>
    </form>
    <button onclick="start()">Calculate!</button>
    <h1 id="yearsres"></h1>Years<br>
    <h1 id="monthsres"></h1>Months<br>
    <h1 id="daysres"></h1>Days<br>
    <h1 id="hoursres"></h1>Hours<br>
    <h1 id="minutesres"></h1>Minutes<br>
    <h1 id="secondsres"></h1>Seconds<br>
    </center>
</body>

JS:

function start() {
    var myVar = setInterval(test(), 1000)
}

function test() {
    console.log("hi");
}

function calculateseconds(sec) {
    var year = document.getElementById("years").value;
    var month = document.getElementById("months").value;
    var day = document.getElementById("days").value;
    var hour = document.getElementById("hours").value;
    var minute = document.getElementById("minutes").value;
    var second = document.getElementById("seconds").value;
    var countdownto = new Date(month + " " + day + "," + " " + year + " " + hour + ":" + minute + ":" + second);
    var epochto = countdownto.getTime()/1000.0;
    var current = new Date();
    var epochcurrent = current.getTime()/1000.0;
    var epochcountdown = epochto - epochcurrent;
    var t = parseInt(epochcountdown);
    var years = 0;
    var months = 0;
    var days = 0;
    var i = 1;

    if(t>31556926){
        years = parseInt(t/31556926); t = t-(years*31556926);       
    }
    if(t>2629743){
        months = parseInt(t/2629743); t = t-(months*2629743);   
    }
    if(t>86400){
        days = parseInt(t/86400); t = t-(days*86400);
    }
    var hours = parseInt(t/3600);
    t = t-(hours*3600);
    var minutes = parseInt(t/60);
    t = t-(minutes*60);


    document.getElementById("yearsres").innerHTML = years;
    document.getElementById("monthsres").innerHTML = months;
    document.getElementById("daysres").innerHTML = days;
    document.getElementById("hoursres").innerHTML = hours;
    document.getElementById("minutesres").innerHTML = minutes;
    document.getElementById("secondsres").innerHTML = t;

}

2 个答案:

答案 0 :(得分:1)

()添加到您的test功能中即可调用它。 setInterval方法引用函数(函数名称)和间隔(以毫秒为单位)。 它可以像这样使用:

function start() {
    var myVar = setInterval(test, 1000);
}

或者像这样:

function start() {
    var myVar = setInterval(function() {
        test();
    }, 1000);
}

此外,如果您需要将参数传递给您的函数,您可以这样做:

function start() {
    var myVar = setInterval(test, 1000, "First param", "Second param");
}

答案 1 :(得分:0)

()移除test() 不知怎的,它会起作用

https://jsfiddle.net/alesmana/u30zmj3t/