You are reading a single comment by @CanyonCasa and its replies. Click here to read the full conversation.
  • @Gordon, Tried this with Espruino board 1v4 and Pico running both 1v89 and 1v84 builds, as well as nightly build from @DrAzzy...

    Executing the following lines from the clearTimeout reference together (i.e. cut and paste both lines into IDE left pane) works as expected...

    var id = setTimeout(function () { print('foo'); }, 1000); // returns 1 and never prints 'foo'
    clearTimeout(id);
    

    But if you enter the first line, wait for the timeout to "fire" (which prints foo), then enter the second line, it results in...

    Uncaught Error: Unknown Timeout
    at line 1 col 16
    clearTimeout(id);

    Obviously, when the Timeout fires it internally clears the Timeout ID, but the code leaves id holding what seems to be a "valid Timeout ID". The code outside the timeout has no way of knowing whether or not the timeout has fired, which prevents arbitrarily cancelling a timeout that has potentially occurred. NodeJS does not exhibit this ambiguous behavior. My workaround has been to use a try/catch clause around the clearTimeout as per the example below...

    var id = setTimeout(function () { console.log('foo'); }, 1000);
    setTimeout(function(){ try {clearTimeout(id);} catch(e) {console.log('error:',e);} },2000);
    
About

Avatar for CanyonCasa @CanyonCasa started