Java code to wait 1000ms before a task
Hi, I want to execute this code after waiting 1000ms. How do I do this?
outlets=1;
patname = this.patcher.box.varname;
bodyobj = this.patcher.getnamed("box");
bodyobj.message("name", patname);
if (!bodyobj) post("Error: patcher does not contain an obj with scripting name yourObjVarname");
To schedule a task take a look at the "Task" object.
A few remarks...
Why do you need to wait to execute global code? In most cases it is better to look for reliable events to execute code. 1000ms after what? Why 1000ms?
If you need to be sure that the patch is fully loaded, use the loadbang function..
Secondly you are defining variables in the global scope of your JS instance without using "var". This will make the variable global across all JS instances, so it might be overwritten in some other place. If you need them to be accessible across JS objects use the "Global" object. Your approach is not advisable for several reasons, including performance.
Cheers,
Jan
Thank you Jan. Those are good questions. This JS code is inside a patcher. Every time I duplicate the patcher the JS code inside it polls the patcher's script name. However, it seems that when I duplicate the patcher, JS polls it before the patcher can rename it self, so the delay would supposedly ensure that that would not happen.
You suggestion is more reasonable. I should use a Loadbang instead so that JS can just wait until the patch is loaded. How do I implement that? The max Loadbang object does not bang when it is duplicated (copy/paste).
Thanks for the tip on adding the "var".
If you check the doc article "JavaScript Basic Techniques" you will see that there is a special function in JS called loadbang
. This function will be called automatically when the patcher containing the [js] is fully loaded and should also fire when duplicating an abstraction. It's the JS equivalent of the loadbang object.
function loadbang() {
// Your code here
}
thank you for the answer Jan. The loadbang function does not bang when the JS object is copy/pasted/duplicated. Only when the patcher is opened for the first time. The same behavior as the max/msp loadbang object.
ah, i misread you, thought you would duplicate an abstraction. Would that be an option, putting the [js] in an abstraction and copy paste that? Otherwise if you have to delay global code I would define a function init()
with everything you need to initialize your instance. Then trigger that function delayed with Task.
Thank you Jan. That worked! sorry for the late reply :)