Is there a more accurate way to create a Javascript timer than setTimeout?

后端 未结 16 2029
礼貌的吻别
礼貌的吻别 2020-11-22 14:11

Something that has always bugged me is how unpredictable the setTimeout() method in Javascript is.

In my experience, the timer is horribly inaccurate in

相关标签:
16条回答
  • 2020-11-22 14:43

    shog9's answer is pretty much what I'd say, although I'd add the following about UI animation/events:

    If you've got a box that's supposed to slide onto the screen, expand downwards, then fade in its contents, don't try to make all three events separate with delays timed to make them fire one after another - use callbacks, so once the first event is done sliding it calls the expander, once that's done it calls the fader. jQuery can do it easily, and I'm sure other libraries can as well.

    0 讨论(0)
  • 2020-11-22 14:46

    I had a similar problem not long ago and came up with an approach which combines requestAnimationFrame with performance.now() which works very effectively.

    Im now able to make timers accurate to approx 12 decimal places:

        window.performance = window.performance || {};
        performance.now = (function() {
            return performance.now       ||
                performance.mozNow    ||
                performance.msNow     ||
                performance.oNow      ||
                performance.webkitNow ||
                    function() {
                        //Doh! Crap browser!
                        return new Date().getTime(); 
                    };
            })();
    

    http://jsfiddle.net/CGWGreen/9pg9L/

    0 讨论(0)
  • 2020-11-22 14:46

    You could consider using the html5 webaudio clock which uses the system time for better accuracy

    0 讨论(0)
  • 2020-11-22 14:48

    Hate to say it, but I don't think there is a way to alleviate this. I do think that it depends on the client system, though, so a faster javascript engine or machine may make it slightly more accurate.

    0 讨论(0)
  • 2020-11-22 14:48

    There is definitely a limitation here. To give you some perspective, the Chrome browser Google just released is fast enough that it can execute setTimeout(function() {}, 0) in 15-20 ms whereas older Javascript engines took hundreds of milliseconds to execute that function. Although setTimeout uses milliseconds, no javascript virtual machine at this point in time can execute code with that precision.

    0 讨论(0)
  • 2020-11-22 14:49

    If you need to get an accurate callback on a given interval, this gist may help you:

    https://gist.github.com/1185904

    0 讨论(0)
提交回复
热议问题