Lag after first animation with jquery

Viewed 45

My goal is to keep the animation smooth from the very beginning as you keep pressing button. What causes the lag after the first animation? How to get rid of it while allowing only one queue at a time?

function move() {
  var queue = jQuery.queue($("#hero")[0], "fx");

  if (queue.length < 2) {
    $('#hero').animate({
      width: '+=30px'
    }, {
      easing: 'linear',
      queue: false,
      duration: 200
    });
  }
}

$(document).keydown(function(e) {
  if (e.keyCode == 68) { //D Right
    $("#hero").queue(function() {
      move();
      $.dequeue(this);
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hero" style="width:10px;height:30px;left:0px;background-color:red;">

</div>

1 Answers

Instead of reacting directly to key down in deciding whether and when to increase your #hero width you need to use the key events to keep track of which keys are down at any given moment, and then check the key state from a setTimeout()-based loop running independent of the key events.

$(function() { // document.ready
  let keys = {};
  let object = $('#hero');

  $(document).keydown(function(event){
    keys[event.which] = true;
  }).keyup(function(event){
    delete keys[event.which];
  });
 
  function move() {
    if (keys[68]) {     // D key
        object.css("width", function(i,oldVal) { 
           return parseInt(oldVal) + 25 + "px"; 
        });
    }
  
   setTimeout(move, 20);
  }

  move();
 
});
#hero {
   transition-property: width;
   transition-duration: 0.2s;
   transition-timing-function: linear;
   transition-delay: 0s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hero" style="width:10px;height:30px;left:0px;background-color:red;">

</div>

Related