• Stars
    star
    1,879
  • Rank 23,693 (Top 0.5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A really simple way to move a function or class to a web worker. 🏋️‍♀️→ 😄

Workly 🏋️‍♀️→ 😄

  • A really simple way to move a stand-alone function/class to a worker thread.
  • Or, expose an object or function in a worker to the main thread.
  • All calls are made asynchronous. Works great with async/await.
  • Only 1kB gzipped.

Install

Download the latest from dist folder

or from npm:

npm install --save workly

Usage

Moving a function to a worker is really simple.

function busyAdd(a, b) {
  let st = Date.now();
  while (true) {
    if ((Date.now() - st) > 2000) break;
  }
  return a + b;
}

(async () => {
  let workerAdd = workly.proxy(busyAdd);
  console.log(await workerAdd(23, 16)); // 39
  // the busyAdd is executed in a worker so
  // the UI does not get blocked
})();

Or, in fact a Class

class Adder {
  constructor() {
    this.count = 0;
  }
  add(a, b) {
    this.count++;
    return a + b;
  }
}

(async () => {
  let WAdder = workly.proxy(Adder);
  let a = await new WAdder(); // instance created/running in worker
  console.log(await a.count); // 0
  console.log(await a.add(23, 16)); // 39
  console.log(await a.count); // 1
})();

Custom workers

The above examples only work when the class/function is not dependent on the containing scope, i.e. other libraries or global objects. But, you can create a custom worker.js file and move the code in there. In the worker, you can expose your object/function/class using workly.expose method.

In this example, the function depends on moment.js

worker.js

importScripts('https://cdn.jsdelivr.net/npm/[email protected]/moment.min.js', '../dist/workly.js');
function friendlyTime(value) {
  return moment(value).calendar(null, {
    sameDay: function (now) {
      if (now - this < 1000 * 60) {
        return "[Just now]";
      } else if (now - this < 1000 * 60 * 60) {
        return "[" + Math.round((now - this) / (1000 * 60)) + " mins ago]";
      } else {
        return '[Today at] LT'
      }
    }
  });
}
workly.expose(friendlyTime);

main.js

(async () => {
  let w = workly.proxy("./worker.js");
  let now = Date.now();
  console.log(now);
  console.log(await w(now));
  console.log(await w(now - (24 * 60 * 60 * 1000)));
  console.log(await w(now - (4 * 24 * 60 * 60 * 1000)));
})();

Caveats

  • If you're not using a custom worker, the function/class being pushed to the worker cannot depend on the containing scope.
  • Since workers do not have access to DOM, DOM manipulation is not supported.
  • Objects passed into functions are not passed by reference, so if the function in the worker updates the passed in object, it will not affect the object in the main scope.

Examples

See the examples folder

License

MIT License (c) Preet Shihn

You may also be interested in

windtalk - Simplest way to communicate between windows or iframes. Work with objects/functions defined in another window or iframe.

More Repositories

1

lumin

A JavaScript library to progressively highlight any text on a page.
JavaScript
545
star
2

legra

LegraJS lets you draw using LEGO like brick shapes
TypeScript
407
star
3

windtalk

Simplest way to communicate with iFrames and other windows
JavaScript
129
star
4

brickception

A fun take on the classic bricks breakout game with popup windows!
TypeScript
115
star
5

rough-paint

Using Houdini CSS Paint API with Rough.js
JavaScript
89
star
6

bezier-points

TypeScript
82
star
7

math-ml

MathML implementation using custom elements
TypeScript
78
star
8

sockly

TypeScript
70
star
9

puppet-canvas

HTML5 Canvas implementation for NodeJS backed by Puppeteer
TypeScript
62
star
10

every-color-picker

Color picker components. Framework independent.
TypeScript
57
star
11

venn

Declarative Venn Diagrams
TypeScript
50
star
12

planar-range

A 2D range component
TypeScript
45
star
13

byproxy

A different way of thinking of web client-server RPC
TypeScript
41
star
14

emoji-slider

A slider control with emojis
JavaScript
41
star
15

base69

Base69 is a binary-to-text encoding scheme inspired by Base64 encoding
JavaScript
38
star
16

points-on-path

Estimate point on a SVG path
TypeScript
34
star
17

rough-draw

Creates a sketchy, hand-drawn version of any image using RoughJS and a WASM version of OpenCV
JavaScript
31
star
18

stippled-image

Custom element to show the stippled version of image
TypeScript
31
star
19

film-strip

TypeScript
25
star
20

proxly

Easiest way to proxy a list of objects/functions in Javascript
JavaScript
24
star
21

path-data-parser

Yet another SVG Path Parser
TypeScript
21
star
22

hachure-fill

Fill a polygon with lines at the specified angle and gap between them
TypeScript
16
star
23

media-pool

A pool of reusable media elements for the web.
TypeScript
16
star
24

alit-element

A simple base class that extends lit-element with some utility functions and adds decorators
TypeScript
12
star
25

csi

https://createsocialimages.com
TypeScript
9
star
26

key-tree

Simple keyed tree data structure 🔑🌲
JavaScript
9
star
27

portcast

Multicasting for Channel Messaging API
TypeScript
8
star
28

genart-tree

Simple generative art
HTML
7
star
29

cielab-dither

Image dithering in the CIELAB color space
TypeScript
7
star
30

flappy-checkbox

TypeScript
6
star
31

sketchy-path

Generate sketchy hand-drawn versions of SVG paths
TypeScript
5
star
32

ecp-website

Nunjucks
4
star
33

no-script

custom element that will block all child script elements from executing
TypeScript
4
star
34

stipple

Stipple
TypeScript
3
star
35

gpt-search-helper

A browser extension to add ChatGPT results to your search results
TypeScript
3
star
36

shihn.ca.apps

Code to accompany blog posts
TypeScript
2
star
37

dag

Basic Directed Acyclic Graph
JavaScript
2
star
38

soso

Sosos Elements
JavaScript
2
star
39

lit-matrix

Matrix math using tagged template literals
TypeScript
2
star
40

virtual-list

Yet another virtual list web component
TypeScript
2
star
41

rough-playground

Silly, tiny, experiments using Rough.js
HTML
2
star
42

recolored-image

Custom element to show image shifted to a different color
TypeScript
2
star
43

undoredo

HTML
1
star
44

byproxy-demo

JavaScript
1
star
45

worker-script

TypeScript
1
star
46

lit-app-utils

TypeScript
1
star
47

roughjs-typescript-example

Sample typescript project using rough.js
HTML
1
star
48

superconductorjs

super conductor js
HTML
1
star
49

navu11

Nunjucks
1
star
50

x-link-title-enabler

Browser extension to add link titles back in the view
TypeScript
1
star
51

bannerdemo

HTML
1
star
52

legra-web

Website for LegraJS
HTML
1
star
53

no-more-script

One script to stop all other scripts
TypeScript
1
star
54

HeyHue

This is going to be the most ultimatest lib to work with colors
JavaScript
1
star
55

cell-canvas

JavaScript
1
star
56

checked-clock

A clock that uses other checked-elements as bits to draw numbers
JavaScript
1
star