1ms 的 setInterval 似乎实际上不是 1ms

setInterval at 1ms doesn't seem to actually be 1ms

我正在尝试使用 HTTPRequest 计算文件下载所需的时间,如下所示:

function getFile() {
    'use strict';
    var url = "data.bin";
    var rawFile = new XMLHttpRequest();
    var timer_var = setInterval( theTimer, 1 );

    rawFile.open("GET", url, true);
    rawFile.onreadystatechange = function () {
        if(rawFile.readyState === XMLHttpRequest.DONE && rawFile.status === 200) {
            toLog(rawFile.responseText);
            window.clearInterval(timer_var);
            toLog("Milliseconds for download: " + time_taken);
        }
    };
    rawFile.send(null);
}

function theTimer() {
    'use strict';
    toLog(time_taken);
    time_taken++;
}

如您所见,我 setInterval 每隔一毫秒调用一次 theTimerthetimer() 所做的只是增加一个变量,理论上应该有一个以毫秒为单位的值,表示间隔 运行.

文件下载完成后,我输出数据,清除计时器并以毫秒为单位显示时间。但是,该值并没有加起来。我应该差不多 2 秒但只站在 250 毫秒左右。

为什么 setInterval 不是真的每 1 毫秒一次?

From the docs:

delay

The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. If this parameter is less than 10, a value of 10 is used. Note that the actual delay may be longer;

(Mozilla,但其他浏览器似乎使用类似的值)

还有对 the documentation of setTimeout 的引用,其中提到 "the actual delay may be longer".

的原因

简而言之:

  • 嵌套超时有最小延迟(已在规范中)
  • 非活动选项卡可能会限制超时以减少负载
  • page/browser/OS 可能忙于其他任务

在现代浏览器中似乎有 a way using window.postMessage

setInterval()setTimeout() 的延迟可能比指定时间长。这有多种原因:

有关详细信息,请参阅 MDN WindowTimers.setTimeout(): Reasons for delays longer than specified

如果将结果乘以 4,它将得到以 ms 为单位的实数。 我刚在 chrome 试过。