What happen if a requestIdleCallback's callback is executed too long to finish in an idle period?

933 views Asked by At

The callback function of a requestIdleCallback will be executed in the browser's idle period. If this callback costs too much time and couldn't be finished in an idle period. And if the user's interaction is coming, does the callback still to be execute and the user's interaction is blocked or the browser will discard the callback and ready to handle the user's interaction?

1

There are 1 answers

0
Kaiido On

The callback itself is not part of the idle period, it's just a task, that has to be ran 'til its end.

Think of it as tasks prioritization, when the event loop will choose what's the next task to execute it will never choose the idle callbacks if there is something else to do, i.e, your idle callbacks have the lowest priority.

But once they are being executed, they will get executed to their end, there is no prioritization scheme anymore, the event loop will simply not run again before it's done with that task, so there is no way it can pass an higher prioritized task.

What could happen though is that you request two callbacks to fire at the same idle period, in that case yes, an other task could occur in between the two callbacks.

As the specs put it:

If the user-agent believes it should end the idle period early due to newly scheduled high-priority work, return from the algorithm

meaning the full list of callbacks doesn't have to be invoked serially.