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

后端 未结 16 2203
礼貌的吻别
礼貌的吻别 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: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/

提交回复
热议问题