setInterval 在 javascript 中循环遍历数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7439519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:08:28  来源:igfitidea点击:

setInterval to loop through array in javascript?

javascriptsetinterval

提问by iosfreak

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.

我有一个网站,他们想要一个新闻自动收报机。目前,我有一个填充它的数组,每隔 x 秒,我希望新闻故事发生变化。

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.

我知道您可以使用setInterval,但它必须通过一个新函数,并且您不能在同一函数中指定某些 javascript 以在它执行时触发。

What are you suggestions?

你有什么建议?

Thanks!

谢谢!

回答by jfriend00

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

您应该使用setInterval()或重复调用setTimeout()。这就是你在未来某个时间在 javascript 中做某事的方式。

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

回答by Drew

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.

您应该尽可能使用 setTimeout。如果您的函数运行时间比间隔时间长,您可能会遇到 cpu 使用率恒定为 100% 的情况。

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

试试这个代码: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.writewith your function.

替换document.write为您的函数。