Skip to content

Latest commit

 

History

History
86 lines (63 loc) · 2.14 KB

README.md

File metadata and controls

86 lines (63 loc) · 2.14 KB

shadow-worker

NPM version License

Use the performance capabilities of web worker in the browser to avoid blocking the main thread

Usage:

npm i shadow-worker #or
npm install shadow-worker --save

Example:

async/await

import { compute } from 'shadow-worker';

await compute(() => [1, 2, 3, 4].map(x => x * 2));
// [2,4,6,8]

const fn = arr => arr.map(x => x * 2);

await compute(fn, [1, 2, 3, 4]);
// [2,4,6,8]

// # debug options
await compute(fn, [1, 2, 3, 4], { label: 'fn', printScript: true });
// data:text/javascript;charset=UTF-8,onmessage=(()=>({data})=>postMessage((arr => {arr.map(x=>x*2)})(data)))(postMessage);
// fn: 16.487060546875ms
// [2, 4, 6, 8]

Promise then

import { compute } from 'shadow-worker';

compute(() => [1, 2, 3, 4].map(x => x * 2)).then(console.log);
// [2, 4, 6, 8]

Browser test

use compute() api
not use

API:

compute()

/**
 * You can easily use `web worker`.
 * Using `web worker` is as easy as using a function, as natural as breathing.
 * The function will `dynamically` help you generate functions that communicate with the worker channel
 * It will be automatically closed when you are finished, so you don't have to worry about the performance problems.
 *
 * @template T
 * @param {(value?: T) => T} callback Function used for `calculation`
 * @param {T} [value] Parameters used for calculation
 * @param {debugOptions} [options={}] Debug option label:`string`,printScript:`boolean`
 * @returns {(Promise<T> | T)} Calculated result
 */

Note: Just in browser node.js side can't use

TODO

  • add test case
  • spuer node side