বড় টাস্ক ছোট ছোট ভাগে ভাগ করা

ওয়েব ফিচার: Scheduler API

ভারী কম্পিউটেশন বা দীর্ঘ লুপ মূল থ্রেডকে ব্লক করতে পারে, যার ফলে পৃষ্ঠাটি কাজ করা বন্ধ করে দেয়। এটি আটকাতে, আপনাকে মাঝে মাঝে ব্রাউজারকে কন্ট্রোল ফিরিয়ে দিতে হবে। scheduler.yield() API আপনাকে একটি বড় টাস্ক পজ করতে এবং ব্রাউজারকে ব্যবহারকারীর ইনপুট বা রেন্ডারিং চালিয়ে যাওয়ার আগে তা ম্যানেজ করতে দেয়।

বড় টাস্ককে ছোট ছোট টাস্কে ভাগ করা

কাজ ভাগ করতে অ্যাসিঙ্ক ফাংশনের মধ্যে 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 API কাজ নাও করতে পারে। কোড যাতে কোনও বাধা ছাড়াই এক্সিকিউট হয় তা নিশ্চিত করতে আপনাকে অবশ্যই 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;
    }
  }
}