How to make loop always running?

Okay, so first I have this code:

let schedule = [
  ["May 21 2018 4:50:00 GMT+0800"],
  ["May 20 2018 11:59:00 GMT+0800"],
  ["May 20 2018 15:21:00 GMT+0800"],
  ["May 20 2018 17:55:00 GMT+0800"],
  ["May 20 2018 19:04:00 GMT+0800"],
  ["May 21 2018 4:40:00 GMT+0800"]
];

for (let i = 0; i < schedule.length - 1; i++) {
    let currentTime = Date.parse(new Date());
    let scheduleNow = Date.parse(schedule[i]);
    let scheduleBefore = Date.parse(schedule[i - 1]);
    if (scheduleNow > currentTime && scheduleBefore < currentTime) {
        someFunction(schedule[i]);
    }
}

I want to make a countdown where when the time is done, the function will run the next scheduled time or something like that. But, the problem is, why it doesn’t do anything?

Sometimes it runs and sometimes it doesn’t, is there something wrong with this code?

Please tell me how to make it works. And how to make it always check when the schedule’s time changed. Thanks.

If I’m not mistaken, and for the code that you have posted, one potential issue (which I think is causing the “sometimes it runs and sometimes it doesn’t” issue that you mentioned, assuming that you have tested with different inputs) is because of the second comparison in the if condition scheduleBefore < currentTime. For example, if I run your code this very moment I’m typing this message, the condition will always evaluate to false because currentTime is always less than any of the Date objects that you can create from the list.

If I haven’t mistaken the program that you described, and if you actually intend to have this code scheduling things in real time, then you need some sort of asynchronous looping mechanism, such as Window.setTimeout or Window.setInterval in the browser, to keep running in the background, in which you check 1. for changes to schedule, 2. if a task is scheduled and should be run, 3. schedule the next task if a you have just completed a task.

I think it could be helpful if you can give a bit more context to what you are making and the code that surrounds it.

In addition to the above, Date.parse(schedule[i - 1]) won’t work when you start i at 0.

i < schedule.length - 1 will never reach the last index in the array.

schedule is an array of arrays of strings rather than an array of strings. Is that intentional? It could cause issues with Date.parse, among other things.