[widget script property] "for" loop delay

for (var i = 0; i < 500; i++) { 
        send('midi:SessionKiano','/note', 1, 72, 1)
}

Is there a way to execute the send function for a number of times at a given delay?


I believe that my tablet's cpu is the kind of cpu that runs faster only when the user does something with it (browsing the web, navigating through files, etc), which is why — sometimes — the midi message is sent less than 500 times (or it fails to be received that many times).
Is there a way add some space between the repeats?

This doesn't work:

for (var i = 0; i < 500; i++) {
setTimeout(function(){
        send('midi:SessionKiano','/note', 1, 72, 1)
}, 50) 
}
// result: the midi message is sent only once

In applescript, I would write:

repeat 500 times
say 'hi' -- here should've been the send() function line
delay 0.05
end repeat

Thank you!

You can use the server's debug mode to verify that if that's important.

For two reasons:

  • setTimeout is immediate, it just tells the browser to execute the action in a given amount of time but doesn't make the loop wait before going to the next iteration. You'd have to multiply the delay amount by i to that effect (warning: 500*50 = 25 seconds).
  • setTimeout is slightly different in widget scripts than in real world javascript: you can't run multiple timeouts in parallel in a single script unless you give them different ids.

This would work:

for (var i=0; i<500; i++) {
  setTimeout(i, function(){ // i used as id
    // do something
  }, i * 10) // 10ms per iteration (5s total)
}
1 Like