"sleep" with JavaScript

Martin.Jirsak's icon

Hi,

Is there any way, how to emulate "sleep" (or "delay"/"pipe" object) in Max with JavaScript? I need to delay sending some data out of JS.

It seems setTimeout doesn't work here.

Thanks

Martin.Jirsak's icon
Nikolas K's icon

Not ideal but have a look at the js task object.
-N

Jan M's icon

A java like "sleep" does not exist in JavaScript. Also note that JavaScript in Max is single threaded and runs in the low priority queue - this means if would have a sleep thread (or emulate it with a long while loop e.g. - it would block your entire Max patch. To schedule a tasks with the Task Object s the correct way to approach this.

@NIKOLAS why do think it's not ideal?

Nikolas K's icon

@Jan I get the use of it, and use it for various functions, but for emulating "sleep" function to be honest, I thinks it is a bit of a fuss! I would prefer a "cleaner" way.

Jorge Suarez's icon

For those looking for an answer and found this post, I have created a "setTimeout" emulation function for max for live JS API.

Code:

function setTimeout(task, timeout){

    this.allowExecution = false;
    
    var tsk = new Task(function (){
            
        if(this.allowExecution){
            
            task();
            
            arguments.callee.task.cancel();
        }
            
        this.allowExecution = true;
            
    }, this);
        
    tsk.interval = timeout;
    tsk.repeat(2);
}

Usage:

setTimeout(function(){
    //Your code here
    post("done!");
}, 1000);
Valery_Kondakoff's icon

Thanks a lot Jorge! Works like a charm.

MartIn 's icon

Thanks too, works great!

Simon O'Rorke's icon

Thanks, Jorge. Just the job!