0

I have a question about auto-updating data when passing local midnight.

Scenario

I am building a web app that contains daily practice content. Similar to Leetcode's everyday problem.

The daily practice will auto-update when passing local midnight.

Thoughts

I have searched a lot about repeating and auto-update posts. But most of them are related to setInterval which is mainly repeating after certain time duration, not to a certain time point.

There are two posts in the community:

How to make Javascript time automatically update

How to get date to auto refresh?


My naive solution:

If I could compromise, not updating exactly at local midnight, I can use setInterval with 24 hours. But it seems weird if a users found content updated at 2:00PM.

My question is: how to realize auto-update when passing local midnight?

Yihan Duan
  • 13
  • 6

1 Answers1

0

Then calculate how much time until midnight, and setTimeout to it. Helper function from https://stackoverflow.com/a/8583781/3807365

function minutesUntilMidnight() {
  var midnight = new Date();
  midnight.setHours(24);
  midnight.setMinutes(0);
  midnight.setSeconds(0);
  midnight.setMilliseconds(0);
  return (midnight.getTime() - new Date().getTime()) / 1000 / 60;
}

function arm() {
  var minutes = minutesUntilMidnight();
  console.log(minutes.toFixed(2) + " minutes till midnight. that's " + (minutes / 60).toFixed(2) + " hours");
  setTimeout(function() {
    // your logic for refreshing here
    window.location.reload();

    // then, re-arm: 
    arm();
  }, minutes * 60 * 1000)
}

// usage:
arm();
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Thanks! It helps a lot. Part of my concern is: The function here seems **only run once**. If I want my app continuously automatically updated, do I need to add extra code like a while loop? – Yihan Duan Jul 04 '22 at 02:47
  • I will update my answer, but in this specific case it doesn't matter since the page reloads and starts over – IT goldman Jul 04 '22 at 07:54
  • Thanks! I will try it soon. One question, I see the code `arm()` recursively call itself. (`arm()` in the `function arm()`). Won't this cause a problem? I remember r**ecursion needs base case**. – Yihan Duan Jul 05 '22 at 22:21
  • Well, it is endless :-) But this isn't really recursion because it doesn't call itself but rather schedules itself ... something like that. – IT goldman Jul 05 '22 at 22:49
  • Cool. Will this endless thing cause some performance issue? Endless sounds like having some potential issue. This question seems naive but I am just so unfamiliar with this part :-( – Yihan Duan Jul 05 '22 at 23:10