Html: Enabling optional higher precedence for 'queueMicrotask'

Created on 7 Sep 2019  路  5Comments  路  Source: whatwg/html

Enqueuing a callback using queueMicrotask: queueMicrotask(() => console.log(42))
or using Promise.resolve(): Promise.resolve().then(() => console.log(42))
currently has the same temporal outcome:

(function() {
   console.log(1)
   Promise.resolve().then(() => console.log(2))
   queueMicrotask(() => console.log(3))
})();
// 1 2 3
// not 1 3 2

It is the correct behaviour, but the usefulness of the new API begins to be less relevant. Clarity apart.

I propose an enhancement, that is the possibility to enqueue a microtask not at the bottom of the microtask queue but at the top of it.
It could be easily implemented using a boolean flag, defaulted to false:

(function() {
   console.log(1)
   Promise.resolve().then(() => console.log(2))
   queueMicrotask(() => console.log(3), true)
})();
// 1 3 2
// not 1 2 3

Most helpful comment

For understanding why queues are often used for scheduling tasks, see e.g. this Wikipedia article and the ones it links to.

For understanding why we should prefer to expose primitives directly, instead of forcing people to get them indirectly through other APIs, see e.g. the extensible web manifesto. For this particular case, you may enjoy https://github.com/whatwg/html/issues/512 or https://github.com/w3ctag/design-reviews/issues/294.

All 5 comments

Interesting idea, though I suspect the code of anyone who uses actually this will become quite a bit more confusing.

Interesting idea, though I suspect the code of anyone who uses actually this will become quite a bit more confusing.

Considering the fact that the Microtask API is primarily designed for libraries implementers, people who know what they're doing, I think it's an acceptable solution.

This isn't possible, as the microtask queue is specifically a queue, so it only allows enqueuing items (at the end), not jumping the queue.

Closing, but happy to continue discussing how the microtask queue works in the closed thread.

@domenic I'd like to ask two things:
1) Why we are forced to use a queue instead of a structure that would allow us to put elements both at the bottom and at the top, to increase priority on demand?
2) Why should I prefer the Microtask API instead of Promise.resolve().then(cb), which has the same outcome but it is more widely supported?

For understanding why queues are often used for scheduling tasks, see e.g. this Wikipedia article and the ones it links to.

For understanding why we should prefer to expose primitives directly, instead of forcing people to get them indirectly through other APIs, see e.g. the extensible web manifesto. For this particular case, you may enjoy https://github.com/whatwg/html/issues/512 or https://github.com/w3ctag/design-reviews/issues/294.

Was this page helpful?
0 / 5 - 0 ratings