javascript - 这段 JavaScript 代码有什么问题?一直循环不停

标签 javascript jquery loops date countdown

我有这个js代码。它有效,但我注意到我收到这样的错误。 “类型错误:document.getElementById(...) 为空” 我注意到 Firebug 中的错误不断计数。所以我假设是 for 循环继续进行。你能看一下下面的代码并告诉我它有什么问题吗?

<script>
$( document ).ready(function() {

    //Create object with the list of due dates
    //The 'name' will correspond to the field ID to populate the results
    var dueDates = {
        'date1':'2017-04-17 09:55:18',
        'date2':'2017-05-17 09:55:18',
        'date3':'2017-06-17 09:55:18'
    };

    var timer = setInterval(function() {
        //Instantiate variables
        var dueDate, distance, days, hours, minutes, seconds, output;
        //Set flag to repeat function
        var repeat = false;
        // Get todays date and time
        var now = new Date().getTime();
        //Iterate through the due dates
        for (var dueDateId in dueDates) {
            //Get the due date for this record
            dueDate = new Date(dueDates[dueDateId]);
            // Find the distance between now an the due date
            distance = dueDate - now;
            // Time calculations for days, hours, minutes and seconds
            days    = Math.floor(distance  / (1000 * 60 * 60 * 24));
            hours   = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            seconds = Math.floor((distance % (1000 * 60)) / 1000);
            //Determine the output and populate the corresponding field
            output = "OVERDUE";
            if (distance > 0)
            {
                output = days + "d " + hours + "h " + minutes + "m " + seconds + "s";
                repeat = true; //If any record is not expired, set flag to repeat
            }
            document.getElementById(dueDateId).innerHTML = output;
            //If flag to repeat is false, clear event
            if(!repeat)
            {
                clearInterval(timer);
            }
        }
    }, 1000);
});
</script>
<div id="date1"></div>
<div id="date2"></div>
<div id="date3"></div>

最佳答案

您的第一个到期日是 future ,因此距离为正,因此repeat在第一次迭代中设置为true循环。由于它在循环内永远不会再次变为 false,因此 clearInterval 函数不会在任何 for 循环迭代中执行。所以1秒后会再次调用setInterval回调,并且重复相同的逻辑...

关于javascript - 这段 JavaScript 代码有什么问题?一直循环不停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43285395/

相关文章:

javascript - 如何增加highchart的高度?

javascript - 自动 jQuery 轮播触发 FancyBox

javascript - Form_Open 始终提交 - 通过 Ajax 提交 - CodeIgniter

vba - 从多个Excel文件中提取特定单元格并将其编译为一个Excel文件

r - 为什么在 rmarkdown 中循环时数据表不打印?

javascript - Jquery 使用 switch 语句关注特定的输入元素

javascript - jquery javascript 问题

javascript - 使用 Turbolinks 定期重新加载 Rails 4 中的页面

jquery - 防止双重表单提交

c++ - 删除所有以//c++ 开头的注释行