Long tasks optimization for website responsiveness

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1215
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    823
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    815

Optimizing Long Tasks for Improved Responsiveness

Long Task is any task on main thread browser execution taking more than 50 milliseconds. While Long Task executes, browser can't process user input: click, scroll, key press. User sees "frozen" interface. 50 ms is perception threshold: delays below 50 ms unnoticed, everything above already "sluggish".

Long Tasks are root cause of poor TTI, TBT and INP. Understanding what causes them—not quick work. No single magic trick.

Diagnosis: Profiling in Chrome DevTools

DevTools → Performance → start recording → simulate load or interaction → stop.

On Main track see red triangles on tasks longer than 50 ms. Click task—call tree appears in bottom panel: which functions called and how long each took.

For production profiling without DevTools:

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log({
      duration: entry.duration,
      startTime: entry.startTime,
      attributions: entry.attribution?.map(a => ({
        containerType: a.containerType,
        containerSrc: a.containerSrc,
        name: a.name,
      })),
    });

    navigator.sendBeacon('/api/longtasks', JSON.stringify({
      duration: entry.duration,
      startTime: entry.startTime,
      url: location.href,
      userAgent: navigator.userAgent,
    }));
  }
});

observer.observe({ type: 'longtask', buffered: true });

Pattern 1: Task Chunking with scheduler.yield()

Most direct way—split task into parts, yield to browser between parts.

Old way via setTimeout(0):

function processLargeArray(items) {
  const CHUNK_SIZE = 100;
  let index = 0;

  function processChunk() {
    const end = Math.min(index + CHUNK_SIZE, items.length);
    for (let i = index; i < end; i++) {
      processItem(items[i]);
    }
    index = end;
    if (index < items.length) {
      setTimeout(processChunk, 0);
    }
  }

  processChunk();
}

Modern way via scheduler.yield() (Chrome 115+):

async function processLargeArrayModern(items) {
  const CHUNK_SIZE = 100;
  for (let i = 0; i < items.length; i += CHUNK_SIZE) {
    const chunk = items.slice(i, i + CHUNK_SIZE);
    chunk.forEach(processItem);
    if (i + CHUNK_SIZE < items.length) {
      await scheduler.yield();
    }
  }
}

Polyfill for browsers without scheduler.yield():

function yieldToMain() {
  if ('scheduler' in self && 'yield' in scheduler) {
    return scheduler.yield();
  }
  return new Promise(resolve => {
    const channel = new MessageChannel();
    channel.port1.onmessage = resolve;
    channel.port2.postMessage(undefined);
  });
}

Pattern 2: Web Workers for CPU-Intensive Work

Move work not touching DOM to Worker. Typical candidates: parsing large JSON, crypto, complex filters, file processing.

// heavy-worker.js
self.onmessage = function({ data: { type, payload } }) {
  let result;
  switch (type) {
    case 'SORT_PRODUCTS':
      result = payload.sort((a, b) => complexSort(a, b));
      break;
    case 'PARSE_CSV':
      result = parseCSV(payload);
      break;
  }
  self.postMessage({ type: type + '_DONE', result });
};

// main.js
const worker = new Worker('/heavy-worker.js');
worker.postMessage({ data: largeArray, operation: 'sort' });
worker.onmessage = (e) => setTableData(e.data);

Pattern 3: requestIdleCallback for Non-Critical Work

Schedule analytics, preloading, state saving for browser idle time:

function scheduleNonCritical(work) {
  if ('requestIdleCallback' in window) {
    requestIdleCallback((deadline) => {
      while (deadline.timeRemaining() > 0 && work.length > 0) {
        const task = work.shift();
        task();
      }
      if (work.length > 0) {
        scheduleNonCritical(work);
      }
    }, { timeout: 2000 });
  } else {
    setTimeout(() => work.forEach(t => t()), 1);
  }
}

Pattern 4: React 18 — startTransition and useDeferredValue

React 18 added mechanism for explicit urgent vs non-urgent updates.

startTransition for non-urgent updates:

function SearchPage() {
  const [inputValue, setInputValue] = useState('');
  const [searchQuery, setSearchQuery] = useState('');

  function handleInput(e) {
    const value = e.target.value;
    setInputValue(value);  // Urgent
    startTransition(() => {
      setSearchQuery(value);  // Non-urgent
    });
  }

  return (
    <>
      <input value={inputValue} onChange={handleInput} />
      <SearchResults query={searchQuery} />
    </>
  );
}

useDeferredValue for lists:

const MemoizedList = memo(function ExpensiveList({ items, filter }) {
  const filtered = items.filter(item => matchesComplexFilter(item, filter));
  return <div>{filtered.map(item => <Item key={item.id} {...item} />)}</div>;
});

function FilteredCatalog({ products, filter }) {
  const deferredFilter = useDeferredValue(filter);
  const isStale = filter !== deferredFilter;

  return (
    <div style={{ opacity: isStale ? 0.7 : 1 }}>
      <MemoizedList items={products} filter={deferredFilter} />
    </div>
  );
}

Pattern 5: Virtualizing Long Lists

Rendering thousands of DOM elements—one big Long Task. Virtualization renders only visible elements.

With @tanstack/react-virtual:

import { useVirtualizer } from '@tanstack/react-virtual';

function VirtualList({ items }) {
  const parentRef = useRef(null);
  const virtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 72,
    overscan: 5,
  });

  return (
    <div ref={parentRef} style={{ height: '600px', overflow: 'auto' }}>
      <div style={{ height: virtualizer.getTotalSize() }}>
        {virtualizer.getVirtualItems().map(virtualItem => (
          <div
            key={virtualItem.key}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              transform: `translateY(${virtualItem.start}px)`,
            }}
          >
            <ListItem item={items[virtualItem.index]} />
          </div>
        ))}
      </div>
    </div>
  );
}

Measuring Result

Before and after lab conditions (Lighthouse, 4× CPU throttle, 3G) and field (INP via web-vitals):

import { onINP } from 'web-vitals/attribution';

onINP(({ value, attribution }) => {
  const { interactionType, interactionTarget, processingStart, processingEnd } = attribution;
  console.log({
    inp: value,
    interaction: interactionType,
    processingTime: processingEnd - processingStart,
  });
});

Typical after full optimization: TBT drops from 1–3 seconds to < 300 ms, INP improves from 400–600 ms to < 200 ms.

Timeframe

Diagnosis of Long Tasks via DevTools + production profiling — 2–3 business days. Full cycle: code splitting, Web Workers, React transitions, virtualization — 2–4 weeks for complex SPA. Simple sites with mostly server rendering — 3–7 business days.