简体   繁体   English

JavaScript延迟1秒钟遍历日期范围

[英]JavaScript Looping through date range with a 1 second delay

I'm trying to loop through a date range and delay going to the next iteration by 1 second. 我正在尝试遍历日期范围,并将下一次迭代延迟1秒。 Each time I run the following in either jsFiddle or Plunker the browser crashes. 每次我在jsFiddle或Plunker中运行以下命令时,浏览器都会崩溃。

  var current_date = new Date("01/13/2013");
  var end_date = new Date("01/20/2013");
  var end_date_time = end_date.getTime();

  while (current_date.getTime() < end_date_time) {
    setTimeout(function () {
      console.log(current_date);
      current_date.setDate(current_date.getDate()+1);
    }, 1000);
  }

Could anyone point me in the right direction as to why this isn't working and how to fix it? 有人能为我指出正确的方向,为什么这不起作用以及如何解决?

You have a blocking loop here. 您这里有一个阻塞循环。 It blocks the whole browser (possibly forever!). 它阻止了整个浏览器(可能永远!)。

while (current_date.getTime() < end_date_time) {
    // do something (it doesn't matter what)
} 

What you need is setInterval : 您需要的是setInterval

var current_date = new Date("01/13/2013");
var end_date = new Date("01/20/2013");
var end_date_time = end_date.getTime();

var interval = setInterval(function () {
    if (current_date.getTime() >= end_date_time) {
       clearInterval(interval);
    }

    console.log(current_date);
    current_date.setDate(current_date.getDate()+1);
}, 1000);

(I didn't check the code for correctness) (我没有检查代码的正确性)

Why does it block the UI? 为什么会阻止UI?

While javascript code is running, the user can't interact with the website and often with the whole browser. 在运行javascript代码时,用户无法与网站进行交互,也无法与整个浏览器进行交互。

When you look at what the browser was doing over time the while() approach looks like 当您查看浏览器随时间的变化时, while()方法看起来像

[while][while][while][while][while][while][while][while][while][while][while]

the interval approach looks like 间隔方法看起来像

[interval]                        [interval]                       [interval]

Only in the free time the browser is able to do other things, for example handling user interaction. 仅在空闲时间,浏览器才能执行其他操作,例如处理用户交互。

You can simply call a timeout if a condition fails: 如果条件失败,您可以简单地调用timeout

function incrementDate(currentDate, endDateTime) {
    currentDate.setDate(currentDate.getDate()+1);

    if (currentDate.getTime() < endDateTime) { 
        setTimeout(function() {
            incrementDate(currentDate, endTime);
        }, 1000);
    }
}

incrementDate(current_date, end_date_time);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM