thread-like

1.2.5 • Public • Published

Thread-like

A tool, which allows you to make non-parallel function work like they are running in separate threads.

npm version

Installation

npm install thread-like
<script src="https://cdn.jsdelivr.net/npm/thread-like/lib/parallelize.js"></script>

Demo

Why?

  • You need to calculate something big
  • It takes a lot of time and blocks the main thread (UI)
  • You want to make it work in parallel

For example, imagine you have to run doSmth() (executes in 1-2 ms) many times:

function longBlockingOperation() {
  let count = 0;
  while (count++ < 2500) {
    doSmth();
  }
}

If you just run it, the page will be blocked for about a second. Enough to think that something is wrong with the service.

DevTools Profiler will show something like this: the thread is blocked for 964 ms by longBlockingOperation.

Profiler with sync execution

thread-like allows you to make such function:

  • run in parallel
  • stoppable
  • non-blocking

Execution will be split into small parts:

API

parallelize(fn*, options)

import { parallelize } from "thread-like";

const config = {}; // optional

const longNonBlockingOperation = parallelize(function* longBlockingOperation() {
  let count = 0;
  while (count++ < 2500) {
    yield doSmth();
  }
  return count;
}, config);
Config Type Default Description
debug boolean false Show debug messages in console
maxTime number null Max time of execution in ms. If null - no limit
  1. You should make target function a generator (function*, more)
  2. You have to mark places for splits with yield

It will be better if there will be at least 0.1 ms between two yields. Otherwise, the time for switching and controlling will be spent more resources, and the execution of the task will be slowed down many times.

Now you can run longNonBlockingOperation and it will run in pseudo-parallel mode.

await

const task1 = longNonBlockingOperation();
const task2 = await longNonBlockingOperation();

Parallelized function returns a Promise, which will be resolved when the task is completed.

abort

You can stop the task at any time:

task.abort(resolve);

It will stop the task, the promise will be resolved or rejected depending on the resolve parameter (true by default). The value in the handler will be the Aborted symbol:

import { Aborted, isAborted } from 'thread-like';
...
try {
  const task = await runTask();
} catch (e) {
  if (!isAborted(e)) { // Или e !== Aborted
    // Abort handling
  }
}

Helpers

Yield every n iterations

Allows to stop execution not every time, but every n iterations.

import { parallelize, everyNth } from 'thread-like';
...
const p = parallelize(function* () {
  let count = 0;
  while (true) {
    count++;
    yield* everyNth(count, 100);
  }
});

Package Sidebar

Install

npm i thread-like

Weekly Downloads

15

Version

1.2.5

License

MIT

Unpacked Size

843 kB

Total Files

40

Last publish

Collaborators

  • kshshe