There is the following code:

$(function(){ var i = 0; document.addEventListener("keydown", function(e){ if(e.which == 49){ $(".box").hide(); i++; $(".count").text(i); setTimeout( function(){ $(".box").show(); }, 5000); } }); }); 
 .box{ width: 100px; height: 100px; background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"></div> <span class="count">0</span> 

When you press the "1" key on the keyboard, the block is hidden and setTimeout is launched, after which the block appears again. There is also a hit counter, but the problem is that you can press the key 1 as many times as you like when the block is hidden, how to disable this event during setTimeout? I found a solution through removing eventListener and adding it after setTimeout, but the code is cumbersome, are there more elegant solutions?

    1 answer 1

     $(function() { var i = 0; var timer = null; document.addEventListener("keydown", function(e) { if (!timer && e.which == 49) { $(".box").hide(); i++; $(".count").text(i); timer = setTimeout( function() { $(".box").show(); timer = null; }, 5000); } }); }); 
     .box { width: 100px; height: 100px; background-color: red; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"></div> <span class="count">0</span>