简体   繁体   中英

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. Each time I run the following in either jsFiddle or Plunker the browser crashes.

  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 :

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?

While javascript code is running, the user can't interact with the website and often with the whole browser.

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]

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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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