Detecting changes to system time in JavaScript

Check in an interval function that the time has not changed too much:

function getTime()  {
  var d = new Date();
  return d.getTime();
}

function checkTime()  {
  if (Math.abs(getTime() - oldtime) > 2000)  {  // Changed by more than 2 seconds?
    alert("You changed the time!");
  }
  oldtime = getTime();
}

var oldtime = getTime();
setInterval(checkTime, 1000);  // Check every second that the time is not off

Tested on Windows with Opera & FF and works flawlessly.


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);

use performance.now() to get duration, which will be independent of system clock

see https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");

And then you can compare performance.now() elapsed with Date.now() elapsed to see whether they are diff too much.