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

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

    Here's an example demoing Shog9's suggestion. This fills a jquery progress bar smoothly over 6 seconds, then redirects to a different page once it's filled:

    var TOTAL_SEC = 6;
    var FRAMES_PER_SEC = 60;
    var percent = 0;
    var startTime = new Date().getTime();
    
    setTimeout(updateProgress, 1000 / FRAMES_PER_SEC);
    
    function updateProgress() {
        var currentTime = new Date().getTime();
    
        // 1000 to convert to milliseconds, and 100 to convert to percentage
        percent = (currentTime - startTime) / (TOTAL_SEC * 1000) * 100;
    
        $("#progressbar").progressbar({ value: percent });
    
        if (percent >= 100) {
            window.location = "newLocation.html";
        } else {
            setTimeout(updateProgress, 1000 / FRAMES_PER_SEC);
        }                 
    }
    

提交回复
热议问题