0

Macro queue trong Javascript

  1. Phân tích đoạn code sau
setTimeout(function a() { console.log("a") }, 1000);
setTimeout(function b() { console.log("b") }, 500);
setTimeout(function c() { console.log("c") }, 2000);

function d() { console.log("d") };
d();
  1. Phân tích từng dòng
  • setTimeout(a, 1000) Đăng ký hàm a, sẽ đưa vào macrotask queue sau ít nhất 1000ms
  • setTimeout(b, 500) Đăng ký hàm b, sẽ đưa vào macrotask queue sau ít nhất 500ms
  • setTimeout(c, 2000) Đăng ký hàm c, sẽ đưa vào macrotask queue sau ít nhất 2000ms
  • d() Gọi trực tiếp, console.log("d") thực thi ngay lập tức
  1. Thứ tự đẩy vào queue
  • Thời điểm Đang xảy ra Macrotask Queue Ghi chú
  • 0ms Hàm d() được gọi (trống) In ra: d
  • ~500ms Timer b hết hạn → đẩy vào queue [b]
  • ~1000ms Timer a hết hạn → đẩy vào queue [b, a] b sẽ thực thi, rồi đến a
  • ~2000ms Timer c hết hạn → đẩy vào queue [b, a, c] c sẽ chờ sau a

All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.