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.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
Use
moment().format("h:mm:ss")
that returns time in ah:mm:ss
format.JSFIDDLE
A better way would be to compute the seconds until midnight. This is very simple and human readable using MomentJS:
So, just do:
JSFIDDLE
There's only really two ways to accomplish this
(1) has been demonstrated in other answers, here's (2).
The first thing to do is calculate the number of milliseconds until midnight then use that as a parameter to javascripts
setTimeout
.After you've finished your work in that function, you might want to recaculate the time until next midnight and repeat the process.
I would try:
Create a date at midnight this morning, add 86400 seconds, and set a timeout for then:
Here's how you'd use it:
So I think you're going about this the wrong way. What you're looking for isn't when it's midnight, you just want to know when the day has changed, which is a much simpler task.
The first thing I'm going to say is avoid using timers at all costs. They're not worth it. The performance hit and extra CPU time you take from running the same function >3600 times a day is ridiculous, especially when it's running on someone else's computer. You don't know how much it can handle, so assume it can't handle much at all. Go easy on your users.
I would suggest listening to a user input event, assuming that this is something you would have on a regular computer, and not something like this, where there is no user input.
If user input events are something you could rely on, I would do this..
If you absolutely need to use a timer, then I would do this..
Keep in mind that the second way is likely to be far less reliable.