Multiple Cores in Javascript

Here’s a cool fiddle: Edit fiddle - JSFiddle - Code Playground

It runs the following which will peg 4 cores which you can see in Activity Monitor on Mac.

window.URL = window.URL || window.webkitURL;

var blob = new Blob(["while(true){}"], {type: 'text/javascript'});

code = window.URL.createObjectURL(blob);

new Worker(code);
new Worker(code);
new Worker(code);
new Worker(code);

Might be an option in Xojo if you are ok using javascript…

Another example where the worker is a javascript file: HTML Web Workers API

Nice example:

From The Basics of Web Workers

That will create a worker, pass a parameter “Hello World” and then the worker will pass the parameter back to the js console.

You can load external js files in the worker using

importScripts('foo.js'); 

Yeah, there are some caveats you have to be aware of (cannot access the DOM, window, document, parent objects + data send to a Web Worker is copied, NOT shared) but Web Workers are pretty cool.

In B4X (Java) we have Background Workers to do this, so for my BANano library (JavaScript in B4X) I transpile the Background Workers to Web Workers so the dev can use the same B4X syntax in their projects.

Both the caller class as the Background Worker can communicate with each other. For more info see [BANano] (v7) Using Background Workers in your WebApps (introduction) | B4X Programming Forum

2 Likes

Another practical example for js based workers is auth0. They use workers to “encapsulate” parts of their authentication process. A kind of frontend-backend to “hide” at least parts of the authentication, as far as that is possible in browsers.

Disclaimer: I don’t use auth0, nor do I like that solution, but I investigated into their offering roughly a 18 months ago. At least at that time it was how their solution worked.

1 Like