Search code examples
javascriptjquerysettimeoutkeyup

Javascript/jquery setTimeout gets faster


I have a bit of code which is a simple counter that starts counting from 0 once spacebar keyup event happens

JavaScript/jQuery

var position = 0;
$(document).on(
    'keyup',
    function (e) {
        if (e.keyCode == 32) {
            count();
        } 
    }
);

function count() {
    if(position < 1000){
        $('.counter').text(position);
        position++;
        setTimeout(function() {
            count();
        }, 500);
    }
}

However while this is running, whenever I press the spacebar again, the increment gets faster and faster the more I press space. Can someone explain to me what is happening here and a way it can be fixed? Here is a link to example code https://jsfiddle.net/hh9doqvb/


Solution

  • That is because each time, you press a space you are initiating a new counter

    var position = 0,
      timer;
    $(document).on('keyup', function(e) {
      if (e.keyCode == 32) {
        if (timer) {
          clearTimeout(timer);
        }
        //if you want to reset the counter when second space is pressed
        position = 0; 
        count();
      }
    });
    
    function count() {
      if (position < 1000) {
        $('.counter').text(position);
        position++;
        timer = setTimeout(count, 500);
      } else {
        clearTimeout(timer);
        timer = undefined;
      }
    }
    body {
      min-height: 200px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <span class="counter"></span>
    <input />


    If you want to ignore the second space onward then

    var position = 0,
      timer;
    $(document).on('keyup.space', function(e) {
      if (e.keyCode == 32) {
        count();
        $(document).off('keyup.space');
      }
    });
    
    function count() {
      if (position < 1000) {
        $('.counter').text(position);
        position++;
        timer = setTimeout(count, 500);
      } else {
        timer = undefined;
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <span class="counter"></span>
    <input />