0

I have written a script to get the top distance of the body to a div, I have 4 divs.

I'd like to set a time out and get each height every 5 seconds.

<div class="printOutputs" id="print1"></div>
<div class="printOutputs" id="print2"></div>
<div class="printOutputs" id="print3"></div>
<div class="printOutputs" id="print4"></div>

I get the ids

var ids = Array.prototype.slice.call(document.querySelectorAll('.printOutputs')).map(function (element) {
  return element.id;
});

Created a for loop - can't seem to get each height every 5 seconds just returns 0s

for (var i=0;i<= ids.length;i++) {
    var limit = ids.length;
    var el = document.getElementById(ids[i]);
   (function(x) {
       setTimeout(function(){
           console.log(getTopPos(el));
           if(x === limit){
               console.log('It was the last one');
           }
       }, 1000 + (3000 * x));
   })(i);
}

Working example here:

https://jsfiddle.net/zidski/nLr9o1x2/

user1177860
  • 509
  • 4
  • 12
  • 24

2 Answers2

0

First, you have 2 loops that are both using the i variable for the iteration and the inner loop keeps overriding the outer i so that after the first outer iteration it ends up being 6 and the outer loop never gets to the second iteration.

Also, you escaped from the closure/scope problem by passing i as an argument to an Immediately-Invoked-Function-Expression so that when your callback runs it will refer to the correct i, but that was only half way because you need to pass the el variable (that is referencing the actual <div> element) as well (otherwise, it will always refer to the last-assigned element in the loop):

for (var j = 0; j <= limit; j++) {
    (function(x, el) {
        setTimeout(function() {
            console.log(getTopPos(el));
        }, 1000 + (3000 * x));
    })(i, el);
}

See Fiddle

haim770
  • 48,394
  • 7
  • 105
  • 133
-1

Why so complicated?? No need to map to the ids, and then find the ids ( why not simply keep the elements in the array?), also you can join the setTimeout and the IIFE into one:

var ids = document.querySelectorAll('.printOutputs');
for (var i=0;i<= ids.length;i++) {
   setTimeout(function(x){//all in one...
       var el = ids[i];
       console.log(getTopPos(el));
       if(x === ids.length-1){
           console.log('It was the last one');
       }
   }, 1000 + (3000 * i),i);
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151