Checkbox: component value not reliable

I like to share with you a surprising behaviour of checkbox values. It is relevant, when you want to trigger a logic based on the change of the checkbox value.

Setup:
Two checkboxes with similar logic. The only difference is, that the logic of checkbox 2 runs after a delay of 500 ms.

Checkbox 1:

Checkbox 2:

The ‘if-condition’ uses the value of the component (=checkbox) to distiguish true/false.
The delay makes them behave in opposite ways (see video). In a more complex app with more logic: the result of checkbox 1 (without a delay) may vary from day to day.

Bottom line: sacrificing speed/performance with a delay, helps to stabilize the logic.

Edit: in the shown example a delay with the ‘waiting time’ of just 1 ms is already sufficient to get the right result at checkbox 2.

Added the behaviour to the bug tracker:

This seemingly weird behaviour happens because you’re reading the component value just as it is about to change. The event contains the new value, but the component value is still the old one. Adding any delay (even 0ms is enough because of how JavaScript works) postpones execution of any following logic, giving the value a chance to update under the hood before you read it.

There’s also much easier way to get checkbox values - bind the checkbox value directly to a variable like so:

image

You can then pretty much ignore the actual checkbox events and focus on the variable state.

-Pekka

Thank you for your description. It is very helpful to know, that the required delay time does not depend (e.g. on the complexity of the app logic ) and that 0 ms give already enough time for all use cases!

Acutally it sounds like a solid way to integrate such a 0-ms-delay into the event ‘Component onChange’ with the next update of Composer (and other onChange-events as well)?
image

Also your hint with binding the checkbox value to a variable is appreciated. Of course that works for the logic in the demo video :smile:
For the demo video I created a separate app project, that is boiled down to the described issue. In ‘real life’ I want to trigger more complex actions :wink: