Skip to main content

Workers

Run CPU-intensive work off the main thread using inline Web Workers. No separate worker files needed — the function is serialized and executed in a worker automatically.

offload

Create a function that runs in a disposable worker:

js
import { offload } from 'weblisk/core/worker.js';

const heavyCalc = offload((data) => {
  // This runs in a Web Worker — no access to DOM
  let result = 0;
  for (let i = 0; i < data.iterations; i++) {
    result += Math.sqrt(i);
  }
  return result;
});

const result = await heavyCalc({ iterations: 10_000_000 });

Each call spins up a one-shot worker that terminates after returning.

workerPool

For repeated tasks, use a persistent pool of workers:

js
import { workerPool } from 'weblisk/core/worker.js';

const pool = workerPool((imageData) => {
  // Process image data in parallel
  const pixels = new Uint8ClampedArray(imageData);
  for (let i = 0; i < pixels.length; i += 4) {
    const avg = (pixels[i] + pixels[i+1] + pixels[i+2]) / 3;
    pixels[i] = pixels[i+1] = pixels[i+2] = avg;
  }
  return pixels;
}, 4); // 4 workers

// Process multiple images in parallel
const results = await Promise.all(
  images.map(img => pool.run(img.data))
);

// Clean up when done
pool.terminate();

The pool size defaults to navigator.hardwareConcurrency (typically 4-16).

Limitations

Functions passed to offload and workerPool must be self-contained: