Scheduling: isInputPending() 方法
Scheduling 介面的 isInputPending() 方法允許您檢查事件佇列中是否存在待處理的輸入事件,這表明使用者正試圖與頁面進行互動。
此功能在您有一個任務佇列需要執行,並且希望定期將控制權交還給主執行緒以允許使用者交互發生的情況下非常有用,從而使應用程式保持儘可能響應和高效能。isInputPending() 允許您僅在有待處理輸入時才交還控制權,而不是必須在任意間隔執行此操作。
警告: isInputPending() 方法已被 Scheduler 介面中的功能(如 yield())取代,這些功能在處理排程任務方面設計得更好。有關更多詳細資訊,請參閱 不要使用 isInputPending()。
isInputPending() 是使用 navigator.scheduling.isInputPending() 呼叫的。
語法
isInputPending()
isInputPending(options)
引數
options可選-
一個提供選項的物件。目前,唯一的選項是
includeContinuous可選-
一個布林值,預設為
false。如果設定為true,則表示在檢查待處理輸入時應考慮連續事件。連續事件是瀏覽器分派的受信任事件,這些事件會連續觸發,例如mousemove、wheel、touchmove、drag、pointermove和pointerrawupdate。
返回值
一個布林值,表示事件佇列中是否存在待處理的輸入事件(true)或不存在(false)。
示例
我們可以在任務執行器結構中使用 isInputPending(),僅當用戶嘗試與頁面互動時才執行 yield() 函式。
function yield() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}
async function main() {
// Create an array of functions to run
const tasks = [a, b, c, d, e];
while (tasks.length > 0) {
// Yield to a pending user input
if (navigator.scheduling.isInputPending()) {
await yield();
} else {
// Shift the first task off the tasks array
const task = tasks.shift();
// Run the task
task();
}
}
}
這可以避免在使用者積極與頁面互動時阻塞主執行緒,從而可能提供更流暢的使用者體驗。但是,透過僅在必要時交還控制權,我們可以在沒有待處理使用者輸入時繼續運行當前任務。這還可以避免任務被排在當前任務之後排程的其他非必需的瀏覽器發起的任務後面。
規範
| 規範 |
|---|
| 輸入事件的早期檢測 # dom-scheduling-isinputpending |
瀏覽器相容性
載入中…
另見
Scheduler介面- Prioritized Task Scheduling API
- Faster input events with Facebook's first browser API contribution (engineering.fb.com, 2019)
- Better JS scheduling with isInputPending() (developer.chrome.com, 2020)
- web.dev 上的最佳化長任務 (2022)