Trying to move your callback at the end of the microtask queue every time you see another was queued after it, is going to be messy and is "fighting" against the FIFO behaviour of the queue.
Instead of trying to give your function a lower priority in the microtask queue, you could try to put your function in queue with lower priority than the microtask queue. Tasks are like that: a new task cannot start before the microtask queue has been depleted.
As in comments you clarify that your function will make final DOM adjustments, you can look at the task that the browser will initiate to update the DOM. This task will process the map of animation frame callbacks before the repaint is performed. So if you schedule your function with requestAnimationFrame, the callback is guaranteed to:
- not execute before the current task completes, i.e. including the execution of any pending microtasks
- execute in a new task (initiated by the browser)
- execute before the next repaint
So the particular goal you have -- to make final DOM adjustments after all other microtasks have done their DOM manipulations, but before they are rendered -- is fulfilled with this approach.
NB: this approach does not prevent that another task might execute between the current task and the task that calls your function. For instance, a setTimeout callback might be able to execute before your function is executed. It is my understanding that this is not problematic for your use case.
Riley Hayes
· 0 rep
· 4 hours ago