zThreader - Pseudo multi threading in JavaScript

What is it ?

A small JavaScript library that provides pseudo-threading for leveraging resources during long, CPU intensive operations.

...

Yes. While more low level languages allow threading to separate a program into individually scheduled chunks where all chunks are ensured to receive an equal amount of resources, JavaScript sadly operates on a single thread.

Nowadays JavaScript is optimized to the extent where its event-driven model and its delegation of delayed operations (for instance: the browsers requestAnimationFrame or setImmediate in node.js) provide a means to keep the application responsive while several tasks are running concurrently.

Though Workers also exist, these provide restrictions as they operate within their own space outside of the main document, thus making it hard to share resources such as Objects allocated elsewhere in memory, the DOM, etc. (Note : this is not necessarily a bad thing and can easily be overcome with post messaging, but sometimes it's just... irritating).

And thus... pseudo-threading!

Which brings us back to zThreader! A "zThread" is basically a function prototype that can be extended / implemented to subdivide a processor-heavy operation into smaller iterations, which will be executed whenever the browser/environment has CPU resources available.

In other words : you can enjoy the number crunching of your ultra cool heavy operation(s), while still keeping the user interface of your application responsive while this operation is running.

Additionally, you can create Java / C-style "daemon" operations (the type that never finish and are running in an eternal "while"-loop, which would otherwise lock script execution when done in JavaScript), finally allowing you to create your awesome "eternally generating Mandelbrot-sets"-application!.

Granted, this form of "fake threading" takes longer to execute as opposed to running the operation in one go, but the benefits of keeping your application feel smooth and responsive PLUS overcoming the dreaded crash as script execution timeouts occur, should make you consider using this approach. Clever benchmarking of your custom operations can make the extra processing time actually negligible.

Available via npm

npm install zthreader