简体   繁体   中英

Checking the current day with moment.js does not update on new day

In a Node application I have a function that runs every 30 seconds.

It prints to the console using moment().day() . I let it run over night and expected it to notice that the day is now 5 instead of 4 signifying that it is now Friday rather than Thursday. It continued to print 4 when I checked this morning. Why would this be?

Here is a jsfiddle https://jsfiddle.net/9ya2auzy/2/

function checkTheDay(){
    setTimeout(function(){
    document.getElementById("out").innerHTML = moment().day(); 
    checkTheDay();
  }, 2000);
}

checkTheDay();

It will output the current day every 2 seconds. If the page is left open, it should run over night and then print the next number, 6 (at the time of writing) rather than the current ouput 5 (at the time of writing).

You're recursing into the checkTheDay function once every two seconds. Over a long enough period of time, you're going to exhaust the call stack.

Use setInterval instead of setTimeout and then you will not need to recurse.

function checkTheDay(){
    setInterval(function(){
    document.getElementById("out").innerHTML = moment().day(); 
  }, 2000);
}

checkTheDay();

You can see the effects of the stack growing in your original fiddle by using the Chrome debugger, setting a breakpoint, and looking at the call stack (upper right in the screenshots below).

First Iteration:

第一次迭代

Second Iteration:

第二次迭代

Third Iteration:

第三次迭代

As you can see, the call stack is growing. Left unchecked, it will grow out of control until it becomes unresponsive or throws an error.

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