Search code examples
javascripthtmljquerysettimeout

resetting timeout on each document click with jquery


I am struggling in getting a timeout timer to reset with each document click interaction. The clearTimeout does not seem to be working.

jquery:

$(document).click(function(e){
  $("#vidBack").hide();
  $(".mainer").show();

  function stopTimer() {
    clearTimeout(timer);
  }

  var timer =  setTimeout(function(){
        $(".bury").hide();
        $(".mainer").hide();
        $("#meetSub").hide();
        $("#leaguesSub").hide();
        $("#memberSub").hide();
        $(".bury").hide();
        $("#welcomeSub").show();
        $("#vidBack").show();
        $("#vida").prop("volume", 0);       
  }, 10000);
});

Solution

  • Refactor your code to something like this:

    var timer;
    
    function resetTimer() {
      if(timer)
        clearTimeout(timer);
      
      $("#vidBack").hide();
      $(".mainer").show();
      
      timer = setTimeout(function() {
        $(".mainer").hide();
        $("#vidBack").show();
      },  5000);
      
    }
    
    $(document).click(resetTimer);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="mainer">mainer</div>
    <div id="vidBack">vidBack</div>