浏览器和nodejs setTimeout的区别

70 阅读1分钟

demo

setTimeout(() => {
  console.log(1);
}, 10);
setTimeout(() => {
  console.log(2);
}, 15);
let now = Date.now();
while (Date.now() - now < 100) {
  //
}
setTimeout(() => {
  console.log(3);
}, 10);
setTimeout(() => {
  console.log(4);
}, 15);
now = Date.now();
while (Date.now() - now < 100) {
  //
}

浏览器

假设初始时间为x,那么

t1 过期时间为x + 10

t2 过期时间为x + 15

t3 过期时间为x + 100 + 10

t4 过期时间为x + 100 + 15

所以输出结果为 1、2、3、4

nodejs

按照timeout划分队列

s10 timeout = 10 有 t1,t3

t1 过期时间为x + 10

t3 过期时间为x + 100 + 10


s15 timeout = 15 有 t2,t4

t2 过期时间为x + 15

t4 过期时间为x + 100 + 15

由于最后有个100的延迟,所以t1、t2、t3、t4都超时了,按照超时的顺序,先执行s10队列,然后再执行s15的队列,因此输出

1、3、2、4