简体   繁体   中英

How to know the approximate position of an enqueued event in a Javascript Engine's event queue?

Suppose we have a flurry of events being generated and being enqueued onto the available Javascript engine's event queue. Is there a method or any industry best practice to estimate the position of a particular event been enqueued?

Any insight on this topic is much appreciated.

There's no standard way to view the event loop's queue programmatically. The only way to know where an event might be in that queue is to know when it was added relative to other events, and to know what kinds of events go where in the event loop.

In modern environments, JavaScript has two kinds of "do this later" queuing: The main event loop (containing "macrotasks"), and a second loop run at the end of each main loop task for any "microtasks" scheduled by that macrotask. On browsers there's also a third thing, requestAnimationFrame (RAF), which is separate from the event loops (while still coordinated with them).

Most event handlers you're familiar with are called as "macrotasks" in the main event loop. setTimeout , DOM events, etc.

Promise completion handlers are called as "microtasks" immediately after the macrotask in which they're queued (so they run before the next macrotask, if any, even if it was queued first).

RAF callbacks are called between macrotasks when the browser is about to repaint, again even if the next macrotask was queued before the requestAnimationFrame callback was.

Example:

 function run() { requestAnimationFrame(function() { log("RAF 1"); }); function log(msg) { var p = document.createElement("pre"); p.appendChild(document.createTextNode(msg)); document.body.appendChild(p); } setTimeout(function() { log("timeout 1"); Promise.resolve().then(function() { log("resolution 2 -- before timeout 2"); }); }, 0); setTimeout(function() { log("timeout 2"); requestAnimationFrame(function() { log("RAF 2"); }); }, 0); setTimeout(function() { log("timeout 3"); requestAnimationFrame(function() { log("RAF 3"); }); }, 0); Promise.resolve().then(function() { log("resolution 1"); }); } function tick() { document.body.innerHTML = ""; run(); setTimeout(tick, Math.random() * 800); } tick();
 pre { margin-top: 0; margin-bottom: 0; }

If you watch that long enough, you'll notice that while the timeouts and promise resolutions are always in the same order, the RAF callbacks occur at various times amongst them (usually at the end, but not always).

Also note how the promise resolutions (microtasks) run before the next macrotask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM