Is there an elegant way to implement a watch update event?

As far as I know (and I know relatively little), there is no native event that is emitted when, for example, the second hand of seconds. The best that I came up with repeatedly checks the Date object (for example, every 333 ms, a shorter interval leads to higher accuracy, but also more resource intensive). Anyway, if I use the same Date object again and again, the time will not be updated, but

Date.prototype.getSeconds() 

logs are "NaN", although typeof is a "number".

  function clock(interval) { var d = new Date(); var secondsOld = d.getSeconds(); d = null; setInterval(function() { var d = new Date(); var secondsNew = d.getSeconds(); if ( secondsNew !== secondsOld ) { secondsOld = secondsNew; // trigger something console.log(secondsOld); } d = null; }, interval); } 
+6
source share
2 answers

You are right that there are no hour cells. The most efficient and accurate way that I would like to approach this problem is to use setTimeout() and Date.now() .

Create a recursive function that calls setTimeout() every second. To be precise, set the timeout duration to the next exact second from the call of this function. Here is an example.

 // milliseconds per second var SECOND = 1000; function bindClockTick(callback) { function tick() { var now = Date.now(); callback(now); setTimeout(tick, SECOND - (now % SECOND)); } tick(); } bindClockTick(function(ms) { console.log('tick! milliseconds: '+ ms); }); 

This uses Date.now() instead of creating a new instance of the Date class.

Here's a JSFiddle to check for accuracy. The demo uses new Date() to easily display the current time, but this can be done in just milliseconds.

+3
source

I'm not sure why you want to sync with the exact second change; however, here is how I do it:

 function clock() { var startMs = Date.now(), startSecs = Math.floor(startMs / 1000), firstOffset = 1000 - startMs % 1000; function tick () { var ms = Date.now(), secs = Math.floor(ms / 1000), dSecs = secs - startSecs; console.log(dSecs); } setTimeout(function () { tick(); setInterval(tick, 1000); }, firstOffset); tick(); } clock(); 

Here's what happens:

  • I grab current time in ms using Date.now ()
  • I determine how many ms until the next second tick ( firstOffset )
  • I set the initial setTimeout to this offset, making sure that it fires on the next next tick.
  • Now that we are synchronized with the second tick, setInterval with 1000 ms will continue to be updated every second.
0
source

Source: https://habr.com/ru/post/969915/


All Articles