开发者

problem with delayed loops

开发者 https://www.devze.com 2023-01-15 13:51 出处:网络
I\'m having a nightmare trying to get some quotes to loop with a delay. I have created the following code:

I'm having a nightmare trying to get some quotes to loop with a delay. I have created the following code:

function loopquotes(){
 var items = $('.comment').size();
 var randomNum = Math.floor(Math.random()*items+1);
 $(".comment:nth-child("+ran开发者_JAVA百科domNum+")").fadeIn('slow').delay(5000);
 $(".comment:nth-child("+randomNum+")").fadeOut('medium');
}

This fades in and out nicely with the delay. However, the loop keeps looping without using the delay and I end up with loads of quotes on the page. Can anybody help me loop this properly so that a new quote is only loaded after the old one has faded out.

Many thanks

David


You can call the function again as a callback, like this:

function LoopQuotes(){
  var comments = $('.comment'),
      rand = Math.floor(Math.random()*comments.length+1);
  comments.eq(rand).fadeIn('slow').delay(5000).fadeOut('medium', LoopQuotes);
}

Then just called this once on page load, e.g. with a document.ready call, like this:

$(LoopQuotes);

What this does is fade in a quote, delay 5000ms, fade it out, then when the .fadeOut() completes, call the function again to pick/show the next quote.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号