• More modern JS world likes the closures... and it is a neat thing, though not really new: Smalltalk had it already in the 70'... and Java tried to make it to really be forgotten... Anyway, took this light timing thing for some brain training... and that is what I came up with: not just one but two versions.

    The first version is more familiar to me. In a nutshell: it does not use the e(vent) and starts the timer immediately, and therefore, it can be started multiple times to just to be killed without timing out. Worst case could be that the light may not go on because there is some time between the event capture that triggers the function call and the checking of the button state by reading the button again... which may (theoretically) be different. There is though no harm, beause the code is 'self healing'.

    var backlight = LED;
    var backlightTimeout;
    pinMode(backlight,"output");
    var backlightOn = function(e) {
      if (backlightTimeout) { clearTimeout(backlightTimeout); }
      backlight.set();
      console.log("Time   : " + getTime());
      backlightTimeout = setTimeout(function(){
        backlightTimeout = undefined;
        if (digitalRead(BTN)) {
          backlightOn();
        } else {
          backlight.reset();
          console.log("Timeout: " + getTime());
        }
      },2000);
    };
    setWatch(backlightOn, BTN, { repeat: true, debouce:50 });
    

    And version 1 related console output:

    Time...: 9395.98322296142```

    Timeout: 9398.59645748138```

    The second version is inspired by you using the e(vent), which creates only timeout when needed and is really taking the value - e(vent).state (Button press/signal change from -state to state) exactly when it happend. What I did not know until now, that there is always an event, but the timeout does not have a state information! This is trigger for further study of the e(vent) objecgt...

    var backlight = LED;
    var backlightTimeout;
    pinMode(backlight,"output");
    backlight.reset();
    var backlightSwitch = function(e) {
      if (backlightTimeout) {
        clearTimeout(backlightTimeout);
        backlightTimeout = undefined;
        if (e.state === undefined) { // was timeout 
          backlight.reset();
          console.log("Timeout: " + getTime());
        }
      } else {
        if (e.state) {
          backlight.set();
        } else {
          backlightTimeout = setTimeout(backlightSwitch,2000);
          console.log("Time   : " + getTime());
        }
      }                                  
    };
    setWatch(backlightSwitch, BTN, { repeat: true, debouce:50 });
    

    And version 2 related console output:

    Timeout: 10316.78362751007```

    Version 2 creates only one timeout, no matter how long the button is held down.

About

Avatar for allObjects @allObjects started