Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

why is the setInterval task executed slower than the setTimeout task in the browser javascript environment? #144

Open
xgqfrms opened this issue Mar 2, 2023 · 2 comments
Labels
setInterval setInterval setTimeout setTimeout

Comments

@xgqfrms
Copy link
Owner

xgqfrms commented Mar 2, 2023

why is the setInterval task executed slower than the setTimeout task in the browser javascript environment?

为什么在浏览器 javascript 环境下 setInterval 任务执行速度比 setTimeout 任务慢?

setTimeout(() => {
  console.log(`4`);
});

let id = setInterval(() => {
  console.log(`5`);
  clearInterval(id);
});

Promise.resolve().then(() => console.log(`2`));

queueMicrotask(() => {
  console.log(`3`);
});

console.log(`1`);

/*

1
2

3
4
5

*/

image

@xgqfrms xgqfrms added setInterval setInterval setTimeout setTimeout labels Mar 2, 2023
@xgqfrms
Copy link
Owner Author

xgqfrms commented Mar 2, 2023

Node.js

setTimeout(() => {
  console.log(`4`);
});

let id = setInterval(() => {
  console.log(`5`);
  clearInterval(id);
});

Promise.resolve().then(() => console.log(`2`));

queueMicrotask(() => {
  console.log(`3`);
});

console.log(`1`);

/*

1
2
3
4
5

*/

image

@xgqfrms
Copy link
Owner Author

xgqfrms commented Mar 2, 2023

let startTime = new Date();
setTimeout(() => {
  let endTime = new Date();
  console.log(endTime - startTime);
}, 0);
for (let i = 0; i < 10**6; i++) {
   // 任务中的同步代码执行时间过长,导致异步宏任务 setTimeout 的执行时间延后 bug
}

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
setInterval setInterval setTimeout setTimeout
Projects
None yet
Development

No branches or pull requests

1 participant