Home > Web Front-end > JS Tutorial > body text

How to Iterate Large Arrays in JavaScript Without Blocking the UI?

Patricia Arquette
Release: 2024-11-04 21:16:02
Original
338 people have browsed it

How to Iterate Large Arrays in JavaScript Without Blocking the UI?

Iterating Large Arrays Asynchronously Without Blocking the UI

Introduction

Iterating over large arrays in JavaScript can be challenging, especially when the UI needs to remain responsive. Blocking the UI can result in a poor user experience. This article explores different approaches to iterating over large arrays without interrupting the UI.

Without Web Workers

When working with code that needs to access the DOM or heavily interacts with other app state, Web Workers cannot be used. A practical solution is to break the iteration into smaller chunks and execute them on a timer. This allows the browser to process other events between chunks, maintaining UI responsiveness.

The following code demonstrates this approach:

<code class="js">function processLargeArray(array) {
  // Customizable chunk size
  var chunk = 100;
  var index = 0;

  function doChunk() {
    var cnt = chunk;
    while (cnt-- && index < array.length) {
      // Process array[index] here
      ++index;
    }

    if (index < array.length) {
      // Set timeout for async iteration
      setTimeout(doChunk, 1);
    }
  }

  doChunk();
}</code>
Copy after login

This code can be further generalized to call a callback function similar to Array.forEach() with customizable chunk size:

<code class="js">function processLargeArrayAsync(array, fn, chunk, context) {
  // Customizable chunk size
  chunk = chunk || 100;
  var index = 0;

  function doChunk() {
    var cnt = chunk;
    while (cnt-- && index < array.length) {
      // Callback called with args (value, index, array)
      fn.call(context, array[index], index, array);
      ++index;
    }

    if (index < array.length) {
      // Set timeout for async iteration
      setTimeout(doChunk, 1);
    }
  }

  doChunk();
}</code>
Copy after login

With Web Workers

If the code does not need to access the DOM, a Web Worker can be utilized. A Web Worker runs independently from the main thread, allowing it to execute long-running tasks asynchronously.

First, the code that will run in the Web Worker needs to be isolated in a separate script. Then, the following steps can be taken:

  1. Create a new Web Worker object and specify the URL of the script:

    <code class="js">var webWorker = new Worker('worker.js');</code>
    Copy after login
  2. Handle the message event received from the Web Worker when it has completed its task:

    <code class="js">webWorker.onmessage = function(e) {
      // Handle the result
    };</code>
    Copy after login
  3. Send data to the Web Worker for processing:

    <code class="js">webWorker.postMessage({ data: array });</code>
    Copy after login

The above is the detailed content of How to Iterate Large Arrays in JavaScript Without Blocking the UI?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template