调用无delay参数的JavaScript setInterval函数:默认延迟值是多少?
Default Delay Value When Omitting
delay in setInterval() Great question — I’ve run into this exact scenario a handful of times when rushing through code, so I looked into it pretty carefully. Let’s break it down:
- ECMAScript Specification Rule: If you don’t provide the
delayparameter at all, or passundefinedexplicitly, it’s treated as if you passed0. The spec explicitly defines this default value for omitteddelayarguments. - Real-World Browser Behavior: Even though the spec says
0, browsers impose a minimum delay threshold (usually around 4ms) for repeated timer executions after the first run. This is an optimization to prevent the event loop from being overwhelmed by overly frequent callbacks. So while the formal default parameter value is0, you won’t get a true 0ms interval in practice: the first callback might fire almost instantly, but subsequent ones will be throttled to that minimum delay.
You can test this easily with a quick code snippet:
let runCount = 0; const startTime = Date.now(); const intervalId = setInterval(() => { runCount++; console.log(`Run #${runCount}: ${Date.now() - startTime}ms elapsed`); if (runCount === 5) clearInterval(intervalId); });
When you run this, you’ll notice the first log is near 0ms, but each following entry is roughly 4ms apart (the exact number might vary slightly by browser).
One quick note: Passing null as the delay will also get coerced to 0, but omitting the parameter entirely is equivalent to passing undefined, which triggers the official default behavior defined in the spec.
内容的提问来源于stack exchange,提问作者Mohammad Sharara
相关产品推荐
相关产品推荐

