You are reading a single comment by @Gordon and its replies. Click here to read the full conversation.
  • But when the handle is lost the timeout never gets cleared, because there is no handle to it.

    This is really not the case... x is just a number, clearing the variable has no effect to clearTimeout since a timeout from setTimeout only runs ONCE. Try it...

    • Do reset() on your Bangle to ensure there's nothing running in the background
    • Run global["\xff"].timers - this lets you see the internal list of timers, and it should be []
    • Run var x then if (x) clearTimeout(x);x = setTimeout(function() { x=undefined; print("Hello") }, 60000)
    • Run global["\xff"].timers again - you'll see a timer
    • Wait 1 minute for the timer to execute and 'Hello' to be written
    • Run global["\xff"].timers and you'll see there are no longer timers

    Shouldn't this be done by clearTimeout?

    Maybe in an ideal world, but it's just the way JS works. Try it on a desktop PC. setTimeout returns an integer, and that integer is never cleared.

    I've tried to give you code that works above, what you suggest is broken for the reasons I already said.

    Perhaps the issue is something else? You can verify it works - just upload this code:

    var chimeTimer;
    
    function planChime() {
      if (chimeTimer)
        clearTimeout(chimeTimer);
      chimeTimer = setTimeout(function() {
        chimeTimer = undefined;
        console.log("Buzz");
        Bangle.buzz().then(() => {
          console.log("Buzz done");
          setTimeout(function(){
             planChime();
          }, 2000);
        });
      }, 60000 - (Date.now() % 60000));
    }
    
    planChime();
    

    It'll chime every minute. Now keep calling global["\xff"].timers - you'll see there is only ever one timer active at a time, which is the one for the next minute.

    What did change a few months ago was how Bangle.buzz works - but the changes there were precisely to stop things like this from happening - it now uses a hardware timer, so people calling clearTimeout() can't accidentally stop the promise from working.

About

Avatar for Gordon @Gordon started