settimeout function is not working well

Posted on
  • Hi people.

    I have some troubles with the settimeout function.
    I have made a switch that an action can happen only one in the time of an interval.
    This cod is not specially meant for the espruino but i have tried this in the browser implemented in a website.
    The code works pretty well but if i click repeatedly fast, then the code ignores the if condition.
    Do i have made a mistake in this codeblock?

    var delay = true;
    function blogPostTimer(){
        if(delay == true){
            delay = false;
            postMessage();
        }else{
            setTimeout(function(){
            delay = true;
            }, 1000 * 5);
        }
    }
    
  • What I think might be happening is that setTimeout gets called lots and never cancelled:

    Call delay before action
    1 true postMessage
    2 false set timeout
    3 false set timeout
    4 false set timeout
    5 false set timeout

    So for instance if you press the button lots, and then 5 seconds after you started, you start pressing it again the original timers that have been added will start to expire and will cause the strange behaviour.

    Why not try moving setTimeout so it only gets called once:

    var delay = true;
    function blogPostTimer() {
        if(delay == true){
            delay = false;
            postMessage();
            setTimeout(function(){
              delay = true;
            }, 1000 * 5);
        }
    }
    

    I'm not sure why it would have worked on a website - personally I'd have thought that it would have the same problem.

    Or if you actually want there to be a 5 second pause between presses (rather than after the first press) then you could actually just cancel the timer and re-set it.

    var delay = true;
    var timeout;
    function blogPostTimer(){
        if(delay == true){
            delay = false;
            postMessage();
        }else{
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout(function(){
             timeout = undefined;
             delay = true;
            }, 1000 * 5);
        }
    }
    
  • Thanks for your solution Gordon!

    Now that you explain me the bug that the setTimeOut called over and over again, i see the problem.
    Sometime the logic is hard to see, even if it's not the most difficult logic.(i am still a beginner :) )

    But anyway, thanks a lot!

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

settimeout function is not working well

Posted by Avatar for Bert-Holland @Bert-Holland

Actions