理解两者区别需要先知道:
- JavaScript 是单线程
- setInterval 是周期性地调用一个函数(一段可执行代码)
- setTimeout 是在一定延迟之后调用一个函数(一段可执行代码)
function cost150ms(){ // 该函数执行 150ms } function testTimeout() { // 函数在 150ms 之后执行 } function testInterval() { // 函数在 150ms、200ms、300ms、400ms... 执行 } setTimeout(testTimeout, 100); setInterval(testInterval, 100); cost150ms();
结论
setTimeout(callable, 100); otherCode();
callable 是周期性执行,不管 otherCode 执行多长时间。
如果到达下一个周期,otherCode 仍然在执行,则 callable 被推迟到 otherCode 执行完毕,即产生“跳过”。
所以上面的例子中能看到 callable 第一次执行是 150ms,第二次执行时 200ms,两次执行只相差 50ms。
假如在某个周期 otherCode 仍在在执行,则该周期 callable 继续被推迟到 otherCode 执行完毕。
setTimeout(callable, 100); otherCode();
callable 调用时间是 otherCode 执行时间与 100ms 最大值。
setInterval 和 setTimeout 都有可能出现推迟执行,setInterval 由于是周期性执行,表现上更像是“跳过”,setTimeout 更像是推迟。
实际场景不会是刚刚等于 150ms、200ms,但接近该值。