The isInputPending()
method of the Scheduling
interface allows you to check whether there are pending input events in the event queue, indicating that the user is attempting to interact with the page.
This feature is useful in situations where you have a queue of tasks to run, and you want to yield to the main thread regularly to allow user interaction to occur so that the app is kept as responsive and performant as possible. isInputPending()
allows you to yield only when there is input pending, rather than having to do it at arbitrary intervals.
isInputPending()
is called using navigator.scheduling.isInputPending()
.
isInputPending()
isInputPending(options)
A boolean that indicates whether there are pending input events in the event queue (true
) or not (false
).
We can use isInputPending()
inside a task runner structure to run the yield()
function only when the user is attempting to interact with the page:
function yield() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
async function main() {
const tasks = [a, b, c, d, e];
while (tasks.length > 0) {
if (navigator.scheduling.isInputPending()) {
await yield();
} else {
const task = tasks.shift();
task();
}
}
}
This allows you to avoid blocking the main thread when the user is actively interacting with the page, potentially providing a smoother user experience. However, by only yielding when necessary, we can continue running the current task when there are no user inputs to process. This also avoids tasks being placed at the back of the queue behind other non-essential browser-initiated tasks that were scheduled after the current one.