0

I'm trying to call a timed function under a number of incrementing variables. The code below executes the function the correct number of times, but only returns the last value of the for loop each time it is called. How would I have the updateBtn function execute using the incrementing loop value?

for(var i = 0; i < myArray.length; i++) {
    setTimeout(function() {
        updateBtn(i);
    }, 6000)
}

function updateBtn(j){
    alert(j);
}
ianmc
  • 23
  • 2
  • 1
    when `setTimeout` fires, `i` is equal to `notPushing.length`. Use an IIFE – Wainage May 16 '16 at 00:12
  • This will create *i* timeouts almost immediately, so they'll all run at almost the same time in about 6 seconds. They will not each run 6 seconds apart. – RobG May 16 '16 at 00:15
  • @RobG That's okay, it's what I want to happen :) – ianmc May 16 '16 at 00:17
  • Probably a duplicate of [*JavaScript closure inside loops – simple practical example*](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – RobG May 16 '16 at 00:18

0 Answers0