0

I have a problem with an animation.

var i = 0;
$('.next').on('click', function() {         
  if (i < 4) {      
        $('li').animate({'left': '-=600px'}, 300);  
        i++;
  }
  console.log($('li:first').position().left);
  console.log(i);
});

$('.back').on('click', function() {
    if ($('li:first').position().left < 0) {    
        $('li').animate({'left': '+=600px'}, 300);
        i--;
  }
  console.log(i);
});

https://jsfiddle.net/6t1wx95f/10/

When you click 4 times on the button 'Next', you will see all the images and everything works fine. But if you click on it many times and very fast, it will stop working and you won't see the last image.

So there are 2 options for me:

  1. The animation should go on (in this case very fast), no matter how fast the button has been clicked.
  2. Wait 300ms until the animation is finished and then go on with i++ or i--;.

What's the easiest way to fix it?

Reza Saadati
  • 1,224
  • 13
  • 27

3 Answers3

0

I guess it's because of your condition check:

if (i < 4) {   
  $('li').animate({'left': '-=600px'}, 300);  
  i++;
}

You are increment variable i for each click on the button, you should somehow disable the button until the animation is over to avoid this.

@edit This answer may help you, he's talking about css animation events. https://stackoverflow.com/a/6210785/8658255

0

Try this approach:

var i = 0;

function next() {
  if (i < 4) {      
    $('li').animate({'left': '-=600px'}, 300);  
    i++;
  }
}

var throttledNext = _.throttle(next, 1200, { leading: true, trailing: false });

$('.next').on('click', throttledNext);

It requires the Lodash and it's _.throttle() method. The essence of throttling is just:

By using _.throttle, we don't allow to our function to execute more than once every X milliseconds.

So all of your intermediate clicks (between the animation phases) will be thrown out.

dhilt
  • 18,707
  • 8
  • 70
  • 85
0

I try to answer my own question and the solution is easy, since what I need is delay().

So instead of $('li').animate({'left': '-=600px'}, 300), I just use $('li').animate({'left': '-=600px'}, 300).delay(600);

https://jsfiddle.net/6t1wx95f/11/

Reza Saadati
  • 1,224
  • 13
  • 27