Reputation: 257
var J_lis = $(".display");
// loop thought each element
J_lis.each(function(g){
g = self.setInterval(function () {
alert("this");
}, 1000);
})
my intention is to set a loop through each element and set a interval to each. so the 1st element go and 2nd element will start after 1000 and so on. but this code wont go 1 by 1 , it will go a quick loop of 4 time and then stop and go 4 times again.
i want it go though each by each and each wait 1000.
for (var f=0; f < J_lis.length; f++){
f = self.setInterval(function () {
// code
}, 1000);
}
this code work just fine like i wanted , but i wanted to set in on jquery each , is there a way of doing it ?
Upvotes: 0
Views: 1982
Reputation: 21489
You should increase delay of interval in loop. Set interval delay relevant to loop index. For example like (index + 1) * 1000
$(".display").each(function(i,ele){
setTimeout(function() {
console.log($(ele).text());
}, (i+1)*1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display">Element 1</div>
<div class="display">Element 2</div>
<div class="display">Element 3</div>
<div class="display">Element 4</div>
<div class="display">Element 5</div>
Upvotes: 1