jean-emmanuel / open-stage-control

Libre and modular OSC / MIDI controller
https://openstagecontrol.ammd.net
GNU General Public License v3.0
705 stars 90 forks source link

[Bug] value is not processed correctly in setTimeout() #820

Closed MaiJianxiang closed 1 year ago

MaiJianxiang commented 1 year ago

Hello,

I created a toggle button with follow onValue script using open-stage-control_1.24.0_win32-x64.

console.log(value)

if (value === 1){
  send('127.0.0.1:6666', '/cue/go', 'Q1')
  setTimeout(()=>{
    console.log('Timeout', value)
    if (value === 1){
      set(this, 0, {external: false})
    }
  }, 3000)
}

if (value === 0){
  send('127.0.0.1:6666', '/cue/stop', 'Q1')
}

I want the function send('127.0.0.1:6666', '/cue/stop', 'Q1') trigger only when the button turn off, and not if it is already off. In the above script, if the button is turned off early within 3 seconds, the value in console.log('Timeout', value) is still 1. This causes the OSC /cue/stop to be sent again.

Or is there an easier way to do this?

Thank you.

jean-emmanuel commented 1 year ago

The anonymous function passed to setTimeout is capturing the value of variable value when created, to make sure you get the most up to date value you should use get(this) instead of value. That being said, I think what you really want to do is cancelling the setTimeout callback when the button is switched off, which you can do simply by calling clearTimeout() in the 2nd if block.

For further usage questions, please use the forums, where other users might help and benefit from the answers.