Skip to content
Advertisement

Display animation complete once even though many animations are fired

I created some code where every time the user clicks the “Go” button the animation starts, and once the animation completes the code prints “Finished”. I want to make it so that, if the user clicks “Go” multiple times before the previous animation ends, don’t print “Finished” for the previous animation but only print it for this one.

How can I do this? Here’s the code I have so far.

$("button").on("click", function() {
  $("p").append("Started...");

  $("div").each(function(i) {
    $(this).fadeIn().fadeOut(1000 * (i + 1));
  });

  $("div").promise().done(function() {
    $("p").append(" Finished! ");
  });
});
div {
  height: 50px;
  width: 50px;
  float: left;
  margin-right: 10px;
  display: none;
  background-color: #090;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>

Advertisement

Answer

Add the totalClick, increase the totalClick for each click, then check if there’s no more totalClick left, display ‘finished!’

let totalClick = 0;

$('button').on('click', function () {
  $('p').append('Started...');

  totalClick++;

  $('div').each(function (i) {
    $(this)
      .fadeIn()
      .fadeOut(1000 * (i + 1));
  });

  $('div')
    .promise()
    .done(function () {
      totalClick--;
      if (!totalClick) {
        $('p').append(' Finished! ');
      }
    });
});
div {
  height: 50px;
  width: 50px;
  float: left;
  margin-right: 10px;
  display: none;
  background-color: #090;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Go</button>
<p>Ready...</p>
<div></div>
<div></div>
<div></div>
<div></div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement