Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting changes to system time in JavaScript

How can I write a script to detect when a user changes their system time in JS?

like image 995
AHOYAHOY Avatar asked Jul 29 '10 22:07

AHOYAHOY


People also ask

How do I know what time my computer changes?

You can use the SystemEvents. TimeChanged event to detect the time changed. However, this will only fire if you have a messagepump running - this is fine for windows client applications, but not so much for most server applications (like services, web apps, etc). Otherwise you can use Environment.

Does JavaScript date use system time?

Yes, it uses the system time on the client side.

How can I check between two dates in JavaScript?

To check if a date is between two dates: Use the Date() constructor to convert the dates to Date objects. Check if the date is greater than the start date and less than the end date. If both conditions are met, the date is between the two dates.


1 Answers

There is no (portable) way to track a variable in JavaScript. Also, date information does not lie in the DOM, so you don't get the possibility of a DOM event being triggered.

The best you can do is to use setInterval to check periodically (every second?). Example:

function timeChanged(delta) {
  // Whatever
}

setInterval(function timeChecker() {
  var oldTime = timeChecker.oldTime || new Date(),
      newTime = new Date(),
      timeDiff = newTime - oldTime;

  timeChecker.oldTime = newTime;

  if (Math.abs(timeDiff) >= 5000) { // Five second leniency
    timeChanged(timeDiff);
  }
}, 500);
like image 172
strager Avatar answered Sep 22 '22 05:09

strager