jottin
jottin

Reputation: 429

Delay Intervals After Each Loop in JQuery

I'm looking at setting a 2-3 second delay on a sprite animation. How do I pause the end of each interval and then continue from 0? I used the code below to run only an interval with no delay at the end.

var imgWidth = 48;
var numImgs = 60;
var cont = 0;

var animation = setInterval(function() {
  var position = -1 * (cont * imgWidth);
  $('#container').find('img').css('margin-left', position);

  cont++;
  if (cont == numImgs) {
    cont = 0;
  }
}, 18);
#container {
  width: 48px;
  height: 48px;
  display: block;
  overflow: hidden;
}

#container img {
  width: 2880px;
  height: 48px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <img src="https://visualcraftsman.com/doh/rdWaitAll.png" alt="My super animation" />
</div>

fiddle

Upvotes: 1

Views: 38

Answers (1)

showdev
showdev

Reputation: 29168

One idea is to use setTimeout() recursively and change the delay depending on the animation's frame number.

// define variables
const $img = $('#container').find('img');
const imgWidth = 48;
const numImgs = 60;
var cont = 0;
var delay = 18;

function advance() {

  // increment frame number, loop back to zero
  cont = cont == numImgs ? 0 : cont + 1;

  // calculate positioning margin
  let position = -1 * (cont * imgWidth);

  // calculate viewing time for this frame
  let delay = cont == 0 ? 1000 : 18;

  // position the image
  $img.css('margin-left', position);

  // schedule next frame advance
  setTimeout(advance, delay);

}

// initiate the recursive loop
advance();
#container {
  width: 48px;
  height: 48px;
  display: block;
  overflow: hidden;
}

#container img {
  width: 2880px;
  height: 48px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <img src="https://visualcraftsman.com/doh/rdWaitAll.png" alt="My super animation" />
</div>

Upvotes: 2

Related Questions