Running javascript processes in background with node.js

José López-Montes's icon

I need advise about handling long processes in Javascript, keeping my patch responsive. Does it exist any equivalent to Web Worker in Max? Is it desirable using any kind of timeout to simulate a background execution? Is it perhaps the right moment for me to switch to Java or even C? Thanks in advance.

José López-Montes's icon

Update: I learned about Task object, and I managed to put an intensive process in Javascript in background, keeping Max very responsive. That's my js code:

var possiblePrime = 2; // to start test of prime numbers
var tick = function () {
    arguments.callee.task.schedule(0);
    findPrimes();
}
var clock = new Task(tick, this, 0);
function start() {
    clock.execute();
}
function stop() {
    clock.cancel();
}
function msg_int(v) {
    possiblePrime = v;
    clock.execute();
}
// really unoptimized and costly function to find prime numbers
function findPrimes() {
    var isPrime = true;
    for (var n = 2; n < possiblePrime; n++) {
        if (possiblePrime % n == 0) {
            isPrime = false;
        }
    }
    if (isPrime) {
        post(possiblePrime + "\n");
        outlet(0, possiblePrime);
    }
    possiblePrime++;
}

I suspect this continuous background processes could be strongly optimized, so any advices or improvements will be highly appreciated.
jlm

js_in_background.js
js
js_process_in_background.maxpat
Max Patch
José López-Montes's icon

I tried a new way with a Node.js server and the maxurl. Apparently is a far more efficient approach.

max-nodejs-maxurl-json-example1.zip
zip
José López-Montes's icon

Update: After some quick tests, Node.js appears to work about 35 times faster than the internal Max JavasScript engine, so I will continue trying to process hard work with Node.js interacting with Max via maxurl.

lyve forms's icon

oh wow, thanks so much for sharing and keep updating this, is exactly one part of what i need. curious about how this evolves. what exactly are you building? can tell you more about what im working on, as well, if ur interested

José López-Montes's icon

Thank you very much for your interest. I´m developing a computer assisted composition engine using some artificial intelligence techniques like metaprogramming based on Javascript, genetic algorithms and functional programming. At the next step I will need to perform long computations, and node.js is far more powerful than Max Javascript engine, and it makes possible a not blocking workflow while using Max. You can get more information here (in Spanish):
http://www.lopezmontes.es/genomus.html
http://espaciosonoro.tallersonoro.com/2016/05/15/microcontrapunctus-metaprogramacion-con-genomus-aplicada-a-la-sintesis-de-sonido/

Rob Ramirez's icon

this is really great, thanks for sharing!