1

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

2
  • Do you want it to pause at the end of each loop? Commented Dec 12, 2022 at 22:57
  • Yes, pause the animation for a couple seconds and then continue from 0. Commented Dec 12, 2022 at 22:58

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

That is definitely more flexible code than mine, thx!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.