Here's a simpler version:
(function() {
var bgIndex = 0;
setInterval(function() {
var item = $('#bg').css({ opacity: 0 });
setTimeout(function() {
item.attr("src", bg[++bgIndex % bg.length]);
}, 300);
}, 10000);
})();
It uses the %
trick to allow your index to cycle through the array without ever leaving the bounds of the array.
Also, this solves the original problem you had because the index variable is only incremented right when you go to use the index so there is no timing delay issue with when the variable is incremented and when it is used.
Summary of enhancements:
- Use
% bl.length
trick to simplify code for staying within the bounds of the array and collapse your two branches of code to only one branch. - Increment array index only when we are just about to use it so there is no timing issue with when it's incremented.
- Wrapped in IIFE so there are no globals. The global
i
is a very dangerous practice. One line of code that forgets thevar
in afor (i = 0;...)
loop and now your globali
gets trounced. - Saved value of
$('#bg')
so you're not regetting that a short time later.