0

The code below works fine, until I tried to add a pause into it. Basically, it will loop through and seem normal, but after a few times it sort of catches up to itself and causes a lot of strange reults. I was curious if there is a better way to achieve what I am going for.

var popups = $('.animate');
var i = 0;
var pT = 2000;
function animatePopup() {
 if (i >= popups.length){
 i = 0;
 }
 popups.eq(i).addClass("show")
 .delay(2000)
 .queue(function() {
 $(this).removeClass("show");
 $(this).dequeue();
 if (i == popups.length) {
 setInterval(animatePopup, pT);
 } else {
 animatePopup();
 }
 });
 i++;
}
animatePopup();
asked Jun 17, 2015 at 14:26
2
  • 1
    Your best bet is to use callbacks. However, it may look confusing. It sure was for me the first time around. Have you tried setTimeout in javascript ? Commented Jun 17, 2015 at 14:27
  • 3
    setInterval runs every pT ms.. you probably meant setTimeout Commented Jun 17, 2015 at 14:29

1 Answer 1

2

Use setTimeout instead of setInterval

setInterval runs the code/function in intervals, with the length of the timeout between them, but it KEEPS RUNNING THEM. On the other hand setTimeout runs once at the end of the specified time

Here's a snippet, if you change setTimeout back to setInterval you'll see it goes crazy too

function recurrentDelayedFunction() {
 
 $('#out').append('ran<br>');
 
 setTimeout(recurrentDelayedFunction, 2000);
}
recurrentDelayedFunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=out></div>

answered Jun 17, 2015 at 14:33
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.