0

I want to run a function in a specific time, and found a solution here :Call a javascript function at a specific time of day

Code:

var now = new Date();
var threepm = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 3, 0) - now;
var twelveam = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 1) - now;

if (threepm < 0) {
        threepm += 86400000; // it's after 3PM, try 3PM tomorrow. 
    }setTimeout(threeamfunction, threepm);

But it doesnt work, so I tried printing both now and threepm without deducting the current time.

New Code:

var now = new Date();
var threepm = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 3, 0);
console.log(now);
console.log(threepm);

And I found out that both times aren't the same.

Result of the log is

2020-05-05T19:26:02.913Z
2020-05-05T16:00:03.000Z

Is this normal? Or am I missing something? The reason why my function isn't running because the difference is too big, even when the time set is the same

Ryan
  • 179
  • 1
  • 1
  • 14
  • "*Is this normal?*" - yes, of course: you were explicitly setting hours, minutes, seconds and milliseconds to `0`, `0`, `3`, and `0` when constructing the `threepm` date. Why would you expect them to be the same? – Bergi May 05 '20 at 19:47
  • For one thing, you're not computing 3:00 pm correctly; the 3 is in the wrong place. – Jack A. May 05 '20 at 19:47
  • You did not copy the code correctly from the answer you found. You're missing the subtraction (without which `< 0` doesn't make any sense either) – Bergi May 05 '20 at 19:48
  • @Bergi i removed the subtraction because i was curious on what would be the result. JackA. I placed the 3 because i want to test it on my current time (its 3 AM here) Ah, i forgot, the 3 was in the first 0, but i was desperate so i tried everything just to see if it works lol – Ryan May 05 '20 at 19:54

1 Answers1

0

Okay, so personally I would go with something like a cron job for scheduling something to happen in a specific time or periodically. I suggest you looking at this library, it is awesome and makes your life simple and easy.

georgekrax
  • 1,065
  • 1
  • 11
  • 22
  • Woah, i didnt know something like this exists! Thank you, sir! – Ryan May 05 '20 at 19:39
  • Always happy to help. Can you upvote my answer please? I would really appreciate it man – georgekrax May 05 '20 at 20:13
  • Welcome brother, you just saved me a lot of time. – Ryan May 05 '20 at 20:15
  • Oh thank you. Was it really this your problem, or just a helpful info for the future? – georgekrax May 05 '20 at 20:18
  • Well, I was looking for a way to run a function in a specific time, so this solved my general problem. I don't have to worry about the date problem anymore. Thank you! – Ryan May 05 '20 at 20:26
  • I do not want to be greedy, but can you also upvote my answer if your reputation allows. I am really happy that I informed you about other features and implementations! – georgekrax May 05 '20 at 20:30