setInterval with an Array

£可爱£侵袭症+ 提交于 2019-12-06 00:00:57

Move the setInterval from the loop.

var arr = ['html5', 'EDM', 'Coca Cola', 'creativity'];
var index = 0;
setInterval(function() {
    console.log(arr[index++ % arr.length]);
}, 4000);​

Live DEMO
No jQuery needed.

Use a recursive setTimeout

var arr = ['html5', 'EDM', 'Coca Cola', 'creativity'];
var alertLoop = function(i) {
    if (arr[i]) {
        alert(arr[i]);
        setTimeout(function(){alertLoop(i+1);}, 4000);
    }
}
alertLoop(0);

Demo: http://jsfiddle.net/B5tJw/

Use of setInterval is discouraged. For an explanation, read here: http://bonsaiden.github.com/JavaScript-Garden/#other.timeouts

To summarise the problem:

setInterval fires the event at a regular interval, regardless of what else is happening on the page.

However, Javascript is not multi-threaded: it can only run one code sequence at a time. If setInterval is triggered while another code sequence is being run, the new code sequence will be blocked until the previous one is finished, and will wait for it.

If this happens repeatedly, you can end up with a large number of events waiting to be run.

You're using alert() to display your messages. alert() causes the code execution sequence to pause until the user responds to the message, but keeps it locked, so that other events cannot run their code. This is a particular problem for setInterval, because it fires new events at the specified time, regardless of whether something else is blocking the script.

The solution is to use setTimeout instead of setInterval.

setTimeout is only triggered once, but it is easy to tell it to trigger itself again inside its own function, so you can get the same effect as setInterval, but with much more control. Your code can wait until after the alert() has been accepted by the user before triggering the next event, which means that you won't get the problem of cascading events that can happen with setInterval.

Hope that helps explain things. The link I mentioned at the beginning is also very helpful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!