Detecting changes to system time in JavaScript

前端 未结 7 1479
猫巷女王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:46

    var last_time = new Date().getTime();
    setInterval(function() {
        var time = new Date().getTime();
        var offset = time - last_time;
        if(offset < 0 || offset > 1500) {
            // Time has been changed
        }
        last_time = time;
    }, 1000);
    

    In theory, this should work. It will check every second to make sure the time hasn't been changed. Note that I use 1100 milliseconds as most JS interpreters don't fire off events at exactly the time specified.

    Hope this helps!

提交回复
热议问题