关于Chrome/Safari/Node 打印的setTimeout()顺序不一致问题

302 阅读1分钟

这两个问题一直没弄明白,暂且记录一下,以后弄明白了再回过头来解答要。 是有小伙伴知道为什么的,可以告诉我一下哈哈。

环境:

  1. Chrome 96.0.4664.110
  2. Safari 12.1.1 (14607.2.6.1.1)
  3. Node v14.17.4

问题一: 为什么 setTimeout() 设置延迟 1ms 会比 0ms 先执行?

setTimeout(() => {
  console.log('setTimeout 1')
}, 1)
setTimeout(() => {
  console.log('setTimeout 2')
}, 0)

打印结果(Chrome/Safari/Node 结果一致)

while
while quit
setTimeout 1
setTimeout 2

问题二: 主线程增加阻塞时间, 打印结果与预期不符, Chrome 的结果和 Safari/Node 不一致

setTimeout(() => {
  console.log('setTimeout 1')
}, 1)
setTimeout(() => {
  console.log('setTimeout 2')
}, 0)
setTimeout(() => {
  console.log('setTimeout 3')
}, 100)

// 阻塞线程 500ms
const beginTime = Date.now()
console.log('while')
while (1) {
  if (Date.now() - beginTime > 500) {
    console.log('while quit')
    break
  }
}

打印结果 (Chrome)

while
while quit
setTimeout 1
setTimeout 3
setTimeout 2

打印结果 (Safari/Node)

while
while quit
setTimeout 1
setTimeout 2
setTimeout 3