The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Jquery looping

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #30688

    Hi folks,

    I am looking to build a kind of news ticker. Effectively I have a p tag and a ul. Id like to loop through the ul and post each li to the p in turn.

    Currently I’m using .each to loop through the li elements. This is working fine but it all happens almost instantly as you would expect.

    What ID really like to do is to add a pause. Any idea how to add that pause?

    I have tried .delay and setting opacity over 1000 ms. The usual tricks.
    These don’t work because they are outside of the loop.

    Any ideas would be fantastic


    Edit: Updated jsFiddle example to be more clear and functional.

    This can be done with the setInterval function native to JavaScript using a ‘global’ counter.

    I created a fairly raw example here at jsFiddle:

    So as you’ll see in the code, the key components are the setInterval and the addItem function.

    var tick = setInterval(function() {
    }, 2000);

    There’s some comments, but I’ll explain this a bit better in case you’re new to javascript. So what this will do is set an interval timer as soon as the script loads that will call the addItem function every 2 seconds, or however long you choose based on the second parameter. The addItem function will then count up the global counter variable (“i” in my example) and use that to set the text of <p> to the list item in the array corresponding to that counter number (starting at 0 of course).

    Being that setInterval will keep running until you kill it, counting up that counter variable will effectively loop through the array in a timed fashion.

    Lastly, in case you’re wondering, I set the interval to a variable so you can kill it if you want later on like this:

    As I said it’s a pretty basic example, but that should be able to set you on your way.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.