wrldbt
wrldbt

Reputation: 191

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

Upvotes: 0

Views: 1118

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241563

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:

First Iteration

Second Iteration:

Second Iteration

Third 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.

Upvotes: 1

Related Questions