0

    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
}
Chun Wai
  • 33
  • 4
  • 1
    See the answers to the [linked question](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). The short version: In a modern environment, your code at the end will work if you change `var i` to `let i` and `var t` to `let t` and remove the `(i)` after the closing `}` of the timer callback function: https://jsfiddle.net/tjcrowder/ob7mtun2/ – T.J. Crowder Mar 19 '20 at 16:04
  • Side note: `` is invalid. Also, `new Array` is almost always better written as `[]`. – T.J. Crowder Mar 19 '20 at 16:05

0 Answers0