Detecting changes to system time in JavaScript

前端 未结 7 1462
猫巷女王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 04:52

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

提交回复
热议问题