tags:

views:

33

answers:

1

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("+randomNum+")").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

+2  A: 

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.

Nick Craver
Hi Nick,Many thanks for that solution its been driving me nuts. I have posted a small fix to your solution as yours does loop correctly, but won't get another quote on the second run through. The below code seems to now work though.
Davemof
function LoopQuotes(){ var size = $('.comment').size(); rand = Math.floor(Math.random()*size+1); $(".comment:nth-child("+rand+")").fadeIn('slow').delay(5000).fadeOut('medium', LoopQuotes);}
Davemof