Search code examples
javascripthtmltimer

setTimeout function with keypress pause Overload


Hi i have a function that is reloading the messages within a div using a timer. Iv tried every possible method that i can get my head round to have a stable timer, but almost every attempt has the timer maxing out running multiple times instead of a stable 1 every 4 seconds. I cannot see what i am doing wrong.

The timer works up until i hit a key , then after the timer restarts i get multiple timers running in the console output.

Can anybody help guide me towards a workable model.

Thank you.

Here is trhe code.

$(window.ready = function(){


var ticker = function (){ 

    var varLISTID = "<?php echo $listID; ?>";
    var varUSERACCOUNTNAME = "<?php echo $useraccountname; ?>";
    var varITEMACCOUNTNAME = "<?php echo $itemaccountname; ?>";
    var varSELECTEDUSER=document.getElementById('datacatchuser').getAttribute("data-variable-SELECTEDUSER");


    var mybutton= "messageboxreplybutton.php?listID=" + varLISTID + "&useraccountname=" + varUSERACCOUNTNAME + "&itemaccountname=" + varITEMACCOUNTNAME + "&selecteduser=" + varSELECTEDUSER;
    $('#buttonbox').load(mybutton);

    var mylink = "loadmessages.php?listID=" + varLISTID + "&useraccountname=" + varUSERACCOUNTNAME + "&itemaccountname=" + varITEMACCOUNTNAME + "&selecteduser=" + varSELECTEDUSER;
    $('#infobox1').load(mylink);

    var myotherlink = "contactselect.php?listID=" + varLISTID + "&useraccountname=" + varUSERACCOUNTNAME + "&itemaccountname=" + varITEMACCOUNTNAME + "&selecteduser=" + varSELECTEDUSER; 
    $('#containercontact').load(myotherlink);
            console.log('running');
};//10s



var myTimer = window.setTimeout(ticker, 4000);

   //stops running until ???
   $(document).keypress(function() {

           window.clearInterval(myTimer);

           setTimeout( function(){
              var myTimer = window.setTimeout(ticker, 4000);

            },4000)
   })


});

Solution

  • When you create a variable (the second time) with

     var myTimer = window.setTimeout(ticker, 4000);
    

    inside a function, you create a new variable local to that function, which is then in accessible later, so you can't clear it. This is why you're ending up with multiple running timers. If you just use one variable that points to the current running interval, you can then clear it before you start another:

    function ticker() {
      console.log("timer fired")
    }
    var myTimer = setInterval(ticker, 1000);
    
    //stops running until ???
    $(document).keypress(function() {
      console.log("clearing")
      clearInterval(myTimer);
      // don't use var, just access the existing variable from the parent scope.
      myTimer = setInterval(ticker, 1000);
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    To run it just once, unless there's a keypress, you can just replace setInterval with setTimeout. This will set a 4 second timer. If there's a keypress, it will cancel the first timeout and reset another.

       function ticker() {
          console.log("timer fired")
        }
        var myTimer = setTimeout(ticker, 4000);
    
        //stops running until ???
        $(document).keypress(function() {
          console.log("resetting timeout")
          clearTimeout(myTimer);
          // don't use var, just access the existing variable from the parent scope.
          myTimer = setTimeout(ticker, 4000);
        })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>