javascript - setInterval 的持续时间

标签 javascript setinterval duration

我创建了一个简单的函数,它在 3 秒内将值从 0 计数到某个值。

这是 fiddle - https://jsfiddle.net/ar6akv5z/和片段:

var number = document.querySelector('.number');
var button = document.querySelector('button');

button.addEventListener('click', function() {
    counting(number, 2500);
})

function counting(elem, value) {
 var count = 0;
 var timerId = setInterval(function() {
  if (++count == value) clearInterval(timerId);
  elem.innerHTML = count;
 }, 3000/value);
}
<span class="number">0</span>
<button>Go</button>

但是函数的持续时间超过了 3 秒。 你能解释一下为什么会这样或者告诉我我的错误吗。

谢谢,对不起我的英语

最佳答案

setTimeout 强制执行了最小延迟和 setInterval .来自 MDN

Reasons for delays longer than specified

Nested timeouts forced to >=4ms

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5.

In fact, 4 ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), the minimum timeout value for nested timeouts was 10 ms.

所以即使您指定了 3000/2500 = 1.2作为间隔时间,它就像您使用了 4作为间隔时间。

关于javascript - setInterval 的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38926655/

相关文章:

javascript - Angular : Passing data back to my controller from a factory ajax call

javascript - 使用 javascript 删除 json 字符串中的反斜杠

javascript - clearInterval() 不工作

vue.js - 如何在 vuejs 中自动刷新 axios 的计算属性

c# - 如何从 mp4、wmv、flv、mov 视频中获取视频时长

flutter - 使用插件 cached_network_image 在 Flutter 中缓存持续时间?

go - 限制格式化持续时间中的有效数字

javascript - 在父 div 中平均分配未知数量的子 div 的高度

javascript - HTML5 混合应用程序的 CORS

javascript - 您可以设置按钮点击的时间间隔吗?