带有数组的setInterval [英] setInterval with an Array
问题描述
我想在 jQuery
中使用 setInterval
函数,以便创建一个内容为每4秒一个阵列。但是我的警报会在很短的时间内显示我的数组的所有值,并在显示所有值后停止4秒。
I'd like to use the setInterval
function in jQuery
in order to create an alert with the content of one array every 4 seconds. However my alerts show all the values of my array within a short amount of time and it stops for 4 seconds after having displayed all the values.
$.each(['html5', 'EDM', 'Coca Cola', 'creativity'], function(id,value) {
setInterval(function(){
alert(value);
}, 4000);
});
在这种情况下,我想显示如下内容: Alert('html5' ) - 4秒 - 警报('EDM') - 4秒 - 警报('可口可乐') - 4秒 - 警报('创造') - 4秒 - 警报('html5') - 4秒 - 警报('EDM' ') - 4秒 - ...
In this case, I'd like to display something like : Alert('html5') - 4 seconds - Alert('EDM') - 4 seconds - Alert('Coca Cola') - 4 seconds - Alert('creativity') - 4 seconds - Alert('html5') - 4 seconds - Alert('EDM') - 4 seconds - ...
推荐答案
使用递归 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);
演示: http://jsfiddle.net/B5tJw/
这篇关于带有数组的setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!