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

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

    .

    REF; http://www.sitepoint.com/creating-accurate-timers-in-javascript/

    This site bailed me out on a major scale.

    You can use the system clock to compensate for timer inaccuracy. If you run a timing function as a series of setTimeout calls — each instance calling the next — then all you have to do to keep it accurate is work out exactly how inaccurate it is, and subtract that difference from the next iteration:

    var start = new Date().getTime(),  
        time = 0,  
        elapsed = '0.0';  
    function instance()  
    {  
        time += 100;  
        elapsed = Math.floor(time / 100) / 10;  
        if(Math.round(elapsed) == elapsed) { elapsed += '.0'; }  
        document.title = elapsed;  
        var diff = (new Date().getTime() - start) - time;  
        window.setTimeout(instance, (100 - diff));  
    }  
    window.setTimeout(instance, 100);  
    

    This method will minimize drift and reduce the inaccuracies by more than 90%.

    It fixed my issues, hope it helps

提交回复
热议问题