var parentDivs = document.querySelectorAll(".parent");
var timer = new Array;
for (var i = 0; i < parentDivs.length; i++) {
fun1(i);
}
function fun1(i) {
var t = 10;
timer[i] = setInterval(function () {
if (t < 500) {
parentDivs[i].style.left = t + "px";
t += 10;
} else {
clearInterval(timer[i]);
}
}, 50);
}
<style>
.parent {
position: relative;
background: yellowgreen;
width: 100px;
height: 100px;
}
</style>
<div class="parent"></div>
</br>
<div class="parent"></div>
</br>
<div class="parent"></div>
</br>
Hello,
The above code use setinterval() in for loop. You can run for testing. It is working now, but could you tell me why use function fun1() to be work. I would like not to use function in for loop , but no luck. How to achieve it without function?
var parentDivs = document.querySelectorAll(".parent");
var timer = new Array;
for (var i = 0; i < parentDivs.length; i++) {
var t = 10;
timer[i] = setInterval(function () {
if (t < 500) {
parentDivs[i].style.left = t + "px";
t += 10;
} else {
clearInterval(timer[i]);
}
}(i), 50); //add a parentheses to execute closure function
}