Detecting changes to system time in JavaScript

前端 未结 7 1461
猫巷女王i
猫巷女王i 2021-01-04 04:04

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

7条回答
  •  独厮守ぢ
    2021-01-04 05:01

    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.

提交回复
热议问题