Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this is because of Javascript beign single threaded?

Tags:

javascript

I came across a snippet like this

(function(){
    for(var i=0;i<3;i++){
    setTimeout(function(){
    console.log(i)
   })
  }
}())

I expected it to log 1,2.... instead it logged 3. Not sure if this is because js beign single threaded,& looking the queue only after finishing the loop.

WORKING COPY

like image 627
brk Avatar asked Feb 09 '23 06:02

brk


1 Answers

It is because JavaScript executes in async manner. When console.log(i) was executing, the for loop completed its iteration and as JavaScript does not have block level scope the value of i in console.log(i) became 3 for all the iterations.

A workaround for this is using IIFE and passing i into the scope:

for (var i = 0; i < 3; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i)
    });

  })(i);
}

Read More about IIFE

like image 57
void Avatar answered Feb 11 '23 00:02

void