Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval with an Array

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

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 - ...

like image 605
JeremyW Avatar asked Apr 10 '26 19:04

JeremyW


1 Answers

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.

like image 71
gdoron is supporting Monica Avatar answered Apr 12 '26 09:04

gdoron is supporting Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!