I have a setTimeout inside the a for loop, but it not behaving as i anticipated.
I have a bunch of banners in a page that are loading all at once. I am removing their parent's div html and storing it in an array. Then I would like for each parent to receive its corresponding html every 5 seconds. This only needs to happen once on ready state.
Here's my code...
function oneBanner() {
var divs = $('.banner-slide'),
imgs = [];
for ( var j = 0; j < divs.length; j++ ) {
imgs.push( $('.banner-slide:nth-child(' + (j+1) + ')') );
}
for ( var k = 0; k < imgs.length; k++ ) {
var url = $(imgs[k]).html();
$(imgs[k]).html('');
setTimeout(function(y) {
console.log(k * 5000);
$(imgs[k]).html(url);
}, k * 5000, k);
}
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<a href="#"> <img src="http://fillmurray.com/150/150" > </a>
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
As you can see the images do not get printed on the screen one at a time every 5 seconds - which I thought I was doing.
Thank you for any help.
Serge