0

I am trying to get a JQuery snippet to loop around and keep displaying the messages in the array. This is what I have so far and it works, it just won't loop round after once even though I have the counter set to 100.

What am I doing wrong? What would be best practice and why?

Thanks in advance

function popMessage() {
    $('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, popMessage);
};

for (var i = 0; i < 100; i++) {
    var messages = [
        "Message 1",
        "Message 2",
        "Message 3",
        "Message 4",
    ].reverse();


    $('#message').hide();
    popMessage();
}
3
  • 1
    @SaadAlothman please be careful with references to w3schools Commented Dec 9, 2013 at 21:41
  • The logic here isn't going to work, the for loop finishes near immediately, then after the 4th time through the array will be empty. Commented Dec 9, 2013 at 21:42
  • Thanks guys, I think I need to do a bit more reading on arrays but your help is appreciated. Good reference @Pointy ! Insightful Commented Dec 9, 2013 at 22:07

1 Answer 1

2

You are removing all the elements but one from the array. Just push it to the beginning for cycle to repeat. Also you can remove that loop it is unnecessary anyways you are invoking the method as callback for fadeOut. Try:

function popMessage() 
{   
    var msg = messages.pop();
    messages.unshift(msg);
    //You can avoid reversing of array and use the below script as well.
    //var msg = messages.shift();
    //messages.push(msg);
    $('#message').html(msg).fadeIn(500).delay(1000).fadeOut(500, popMessage);
};

Demo

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

2 Comments

@user3072619 You dont need that loop.
Thank you for your really detailed reply! I can't believe I overlooked this one. Thanks again!

Your Answer

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