• You invoke clearWatch(handle) with invalid handle. Behavior is absolutely correct.

    Best pattern for dealing with setWatch() and clearWatch() is:

    var watchIdX = undefined;
    ...
    watchIdX = setWatch(...);
    ...
    watchIdX = clearWatch(watchIdX);
    ...
    // and to make it safe:
    if (watchIdX) watchIdX = clearWatch(watchIdX);
    

    If your watch is a single shot, you also have to clear the watch handle...

    var watchIdX = undefined;
    ...
    watchIdX = setWatch(function(...) {
        watchIdX = undefined;
      ... }, pinY, {repeat:false, ...} );
    

    (EDITED) Before a recent release, clearWatch(undefined) and clearInterval(undefined) were handled lick without argument and that lead to unintentional clearing of all watches, timeouts and intervals. Clearing all watche, intervals and timeouts produces unpredictable results, as it is easy to understand in a (timer) interrupt driven context. (thanks @AkosLukacs - see post #16).

    The other challenge you may face in your code is asynchronous behavior: some code issues a command to a (peripheral) device to prepare some data, then you have to wait for sending another command to receive - pull / get - the prepared data and then process that data. Even pulling the prepared data involve the pattern of repeated, asynchronous pulling of pieces of data until the data gram is complete. The basic solution technique is callbacks, and in elegant form it is Promises. Trying to delay is always a lottery in regard to delay enough... and if it works, it slows overall application flow unnecessarily down.

    Another safe approach I choose is to start active code within the onInit(){ ... } function in order to let the upload complete BEFORE acting code (with setWatch, setInterval, setTimeOut) - code on level 0 / immediate code - is executed.

  • Re: clearWatch / clearInterval:

    • calling clearWatch without arguments is valid, and clears all watches
    • calling clearWatch(undefined) throws an error. To avoid the mistake when you had a watch / interval number stored, cleared it, cleared the number, but call it again, but now accidentally clear all watches
About

Avatar for AkosLukacs @AkosLukacs started