gpt4 book ai didi

javascript - setInterval 的持续时间

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:12:28 25 4
gpt4 key购买 nike

我创建了一个简单的函数,它在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com