开发者

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 fu开发者_开发知识库nction to fire when it does.

What are you suggestions?

Thanks!


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);


You should whenever possible use setTimeout. If your function takes longer to run than the interval, you can run into a constant 100% cpu usage situation.

Try this code: http://jsfiddle.net/wdARC/

var stories = ['Story1','Story2','Story3'], 
    i = -1;
(function f(){
    i = (i + 1) % stories.length;
    document.write(stories[ i ] + '<br/>');
    setTimeout(f, 5000);
 })();

Replace document.write with your function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜