Juan Jardim Juan Jardim - 6 months ago 91
Javascript Question

Best Way to detect midnight and reset data

I've been developing a web application Dashboard and I was wondering how to detect that is midnight in order to reset some arrays that contains datas from the previous day using jquery or momentjs.

Answer

Use moment().format("h:mm:ss") that returns time in a h:mm:ss format.

var midnight = "0:00:00";
var now = null;

setInterval(function () {
    now = moment().format("h:mm:ss");
    if (now === midnight) {
        alert("Hi");
    }
    $("#time").text(now);
}, 1000);

JSFIDDLE

A better way would be to compute the seconds until midnight. This is very simple and human readable using MomentJS:

// returns the number of seconds until next midnight
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds');

So, just do:

setTimeout(
   midnightTask,
   moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds')
);

function midnightTask() {
  /* do something */
}

JSFIDDLE