ज़्यादा कंप्यूटेशन या लंबे लूप, मुख्य थ्रेड को ब्लॉक कर सकते हैं. इससे पेज काम करना बंद कर सकता है. इससे बचने के लिए, आपको समय-समय पर ब्राउज़र को कंट्रोल वापस देना चाहिए. scheduler.yield() एपीआई की मदद से, ज़्यादा समय लेने वाले किसी टास्क को रोका जा सकता है. इससे ब्राउज़र को उपयोगकर्ता के इनपुट या रेंडरिंग को मैनेज करने का मौका मिलता है. इसके बाद, टास्क को फिर से शुरू किया जा सकता है.
ज़्यादा समय लेने वाले टास्क को छोटे-छोटे टास्क में बांटना
काम को छोटे-छोटे हिस्सों में बांटने के लिए, एसिंक फ़ंक्शन में scheduler.yield() का इस्तेमाल करें.
async function processLargeArray(items) {
// DO: Set a time-based deadline 50 milliseconds into the future. 50
// milliseconds is the boundary for when a task becomes a long task.
let deadline = performance.now() + 50; // 50ms budget
for (const item of items) {
// Process the item
processItem(item);
// MANDATORY: Yield to the main thread periodically to keep the UI
// responsive. This can be done by checking if the deadline set earlier
// has been exceeded. When it has been, yield, then reset the deadline
// another 50 milliseconds into the future.
if (performance.now() >= deadline) {
await scheduler.yield();
deadline = performance.now() + 50;
}
}
}
फ़ॉलबैक रणनीतियां
ऐसा हो सकता है कि कुछ ब्राउज़र में scheduler एपीआई काम न करे. आपको setTimeout का इस्तेमाल करके फ़ॉलबैक लागू करना होगा, ताकि कोड बिना किसी रुकावट के एक्ज़ीक्यूट हो सके.
scheduler.yield() के लिए फ़ॉलबैक
async function processLargeArrayWithFallback(items) {
// DO: Set a time-based deadline 50 milliseconds into the future.
let deadline = performance.now() + 50;
for (const item of items) {
processItem(item);
// MANDATORY: Yield to the main thread periodically to keep the UI responsive.
if (performance.now() >= deadline) {
// DO: Feature detect scheduler.yield
if ('scheduler' in window && 'yield' in window.scheduler) {
await scheduler.yield();
} else {
// DO: Fallback to setTimeout for older browsers
await new Promise(resolve => setTimeout(resolve, 0));
}
deadline = performance.now() + 50;
}
}
}