Home > OS >  Strange Loop behaviour with delays (jQuery)
Strange Loop behaviour with delays (jQuery)

Time:03-05

I build a simple Loop in jQuery but the "price" pops up randomly. I think there's some trouble with the delays but i want it to stay for like 4-5 seconds.

setInterval(function(){loop()}, 16000);
 
function loop(){
  $('.popup').fadeIn('1000');
    $('.twitchad').animate({
    left: "-100px"
  }, 1500, function() {
    $('.price').show().animate({
          left: 50
      }).delay('4000').fadeOut("slow");
    $('.popup').delay('5000').fadeOut("slow");
  });
}

CodePudding user response:

If you add a count, you can see better whats happening:

var now = Date.now();

function secondsCount(){
  return Math.floor((Date.now() - now)/1000);
}

setInterval(function(){
  console.log("Loop", secondsCount());
  loop();
}, 10000);
 
function loop(){
  console.log("Trigger FadeIn", secondsCount());
  $('.popup').fadeIn('1000');
  console.log("Trigger Animate Left", secondsCount());
    $('.twitchad').animate({
    left: "-100px"
  }, 1500, function() {
    console.log("Trigger Fadeout", secondsCount());
    $('.popup').delay('5000').fadeOut("slow", function(){
      console.log("Complete", secondsCount());
    });
  });
}

In console, I see the following.

Loop 10 
Trigger FadeIn 10 
Trigger Animate Left 10 
Trigger Fadeout 11 
Complete 17 
Loop 20 
Trigger FadeIn 20 
Trigger Animate Left 20 
Trigger Fadeout 21 
Complete 27 
Loop 30 
Trigger FadeIn 30 
Trigger Animate Left 30 
Trigger Fadeout 31
Complete 37

It is looping and triggering everything in a proper cycle, yet I suspect after the first run, it is not in the exact state you expect. It's not clear what you were expecting or what you see that is wrong from your post. Hopefully this help you get there. If not, update your post with details or screen shots that might help explain.

  • Related