zThreader

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.

(note: while Node 10.5 introduced worker threads, this is not (yet) a browser solution)

Nowadays JavaScript is optimized to the extent where its event-driven model and its delegation of delayed operations provide a means to keep the application responsive while several tasks are running concurrently.

Though Web Workers exist to provide an execution stack separate from the main window, 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, Window API's, etc.

(note: this is not necessarily impossible depending on your use case and can easily be overcome with post messaging, but sometimes it's cumbersome).

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.

When should I use this?

Good question (text updated in 2021) :

Nowadays there are plenty of different ways to maintain application performance while running computation heavy operations. Consider using Web Workers and/or WebAssembly for your applications. More and more API's overcome restrictions / provide alternatives to Window API's or shared memory usage.

If you however need to tweak a legacy application that requires browser API's unavailable to Workers or don't want to introduce post messaging overhead, you can reach for zThreader to provide a quick solution to unresponsive pages being killed by the browser.

Available via npm

npm install zthreader