Socket
Socket
Sign inDemoInstall

web-worker-helper

Package Overview
Dependencies
0
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    web-worker-helper

Utilities for running tasks on worker threads


Version published
Weekly downloads
36K
increased by3.34%
Maintainers
1
Install size
400 kB
Created
Weekly downloads
 

Changelog

Source

0.0.4

Patch Changes

Readme

Source

web-worker-helper

Forked from @loaders.gl/worker-utils implementation

Time consuming task

// fibonacci.js
export function fibonacci(n: number) {
  let n1 = 1,
    n2 = 1,
    sum = 1;
  for (let i = 3; i <= n; i += 1) {
    sum = n1 + n2;
    n1 = n2;
    n2 = sum;
  }
  return sum;
}

Creating workers for time-consuming task

// fibonacci.worker.js
import { createWorker } from 'web-worker-helper';
import { fibonacci } from './fibonacci';

createWorker(async (data: number) => {
  const result = fibonacci(data);
  return result;
});

Bundle worker

Main thread call worker

  1. parse worker
import { WorkerFarm } from 'web-worker-helper';

export async function parseWorker(
  workerName: string,
  data: any,
  options?: Record<string, any> = { maxConcurrency: 3, reuseWorkers: true }
) {
  const url = getWorkerURL({ name: workerName });
  // const source = `fibonacci codeString`
  const workerFarm = WorkerFarm.getWorkerFarm({
    maxConcurrency: options.maxConcurrency,
    reuseWorkers: options.reuseWorkers,
  });
  const workerPool = workerFarm.getWorkerPool({ name: workerName, url });
  // const workerPool = workerFarm.getWorkerPool({ name: workerName, source });
  const job = await workerPool.startJob(workerName, (job, type, data) => job.done(data));

  job.postMessage('process', { input: data });

  const result = await job.result;
  return result.result;
}
  1. Call time-consuming task
import { parseWorker } from './parse-worker';
import { fibonacci } from './fibonacci';

export async function starFibonacci(iskorker, data) {
  if (iskorker) {
    const result = await parseWorker('fibonacci-worker', data, {});
    return result;
  }

  const result = await fibonacci(data);
  return result;
}

Keywords

FAQs

Last updated on 07 Apr 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc