0

My title may be undescriptive but this is my problem. I have a for loop thats doing a get requests in jquery but I can't read any defined local variables thats in the for loop as it gets rewritten as the loop continutes

for(i=0;i<10;i++){
    var Something = i 
    $.get("http://example.com",function(){
        console.log(Something)
    })
}

the output would be 10 10 10 10 10 10 10 10 10 10

How would I go about passing the Something variable into the function?

John Smith
  • 347
  • 1
  • 11
  • Note this is because `$.get` is ran after the for loop finished, it's asynchronous. – Spencer Wieczorek Jul 12 '16 at 03:23
  • The linked duplicate covers the general principle here. [This question](http://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-consecutive-values?noredirect=1&lq=1) will probably help too, as might some of the other linked questions about asynchronous code in a loop. Note also that `var` creates a variable local to the containing *function*, not local to the loop. (Or a global variable, if not in a function.) Using `let` instead solves the problem if you don't need to support old browsers. – nnnnnn Jul 12 '16 at 03:27

0 Answers0