• 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);
        }
    }
    
About

Avatar for Gordon @Gordon started