I have two functions
function getImgStr(imgName){
thisStr = '<img src="/_shared/img/discovery/200x100/'+imgName+'.jpg">';
return thisStr;
}
function buildIt(imgSrc){
console.log(imgSrc);
$('#content').append('<div></div>');
$('#content div:last').hide()
.addClass('imgBox')
.attr('id',imgSrc)
.html(getImgStr(imgSrc))
.slideDown(2000);
}
I have an array that I am looping
$(function(){
for(i=0;i<=imgList.length-1;i++){
buildIt(imgList[i]);
}
});
works fine, no probelms.
But when I try to wrap this is a setInterval is barfs
$(function(){
for(i=0;i<=imgList.length-1;i++){
var loadIt = setInterval(function(){
buildIt(imgList[i]);
},1000);
}
});
the console.log in buildIt is undefined when the setInterval is there so I am assuming that the interval somehow affects the loop but I do not understand what I am doing wrong. Any ideas?
Per your clarification: If you want to load images one after the other every second, you can do something like this. You don’t need a loop at all.
What this does is initialize the value of
ito 0.ifunctions exactly likeiin your for loop. It’s essentially an index. Then, you store the value of the interval inside the variableid. This way you maintain a reference to the interval so that you can clear it when you are done loading the images.Finally, inside the interval function you check to see if
iis equal to the length of the number of images in your image list. If it is, we know that we’re done loading all of them so we clear the interval. Otherwise we call thebuildItfunction for the image that corresponds to the current value ofiand the increment the value ofi.