Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval to loop through array in javascript?

I have a website where they want a news ticker. Currently, I have a array that populates it, and every x seconds, I want the news story to change.

function startNews(stories) {

}

I am aware that you can use setInterval, but it has to go through a new function and you can't specify certain javascript in the same function to fire when it does.

What are you suggestions?

Thanks!

like image 360
iosfreak Avatar asked Sep 16 '11 02:09

iosfreak


People also ask

Is setInterval a loop?

The setInterval method in JavaScript acts like a traditional loop but on a delay.

Does setInterval repeat?

setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

Is setInterval infinite?

setInterval() takes a function argument that will run an infinite number of times with a given millisecond delay as the second argument. Just like setTimeout() , additional arguments can be added beyond the delay, and these will be passed on to the function call.

Does setInterval execute immediately?

This property can be used in the callback of the setInterval() function, as it would get immediately executed once and then the actual setInterval() with this function will start after the specified delay.


1 Answers

You should use either setInterval() or repeated calls to setTimeout(). That's how you do something in javascript at some time in the future.

There are no limitations on what you can do with either of those timer functions. What exactly do you think you cannot do that is making you try to avoid them?

Here's a pseudo code example:

var newsArray = [];   // your code puts strings into this array
var curNewsIndex = -1;

var intervalID = setInterval(function() {
    ++curNewsIndex;
    if (curNewsIndex >= newsArray.length) {
        curNewsIndex = 0;
    }
    setTickerNews(newsArray[curNewsIndex]);   // set new news item into the ticker
}, 5000);

or it could be done like this:

var newsArray = [];   // your code puts strings into this array
var curNewsIndex = -1;

function advanceNewsItem() {
    ++curNewsIndex;
    if (curNewsIndex >= newsArray.length) {
        curNewsIndex = 0;
    }
    setTickerNews(newsArray[curNewsIndex]);   // set new news item into the ticker
}

var intervalID = setInterval(advanceNewsItem, 5000);
like image 98
jfriend00 Avatar answered Oct 20 '22 00:10

jfriend00