Is this because Javascript beign is the only thread?

I came across a fragment similar to this

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

I expected it to write 1,2 .... instead it is logged 3. I am not sure if this is because js beign single threaded, & looking in line only after the loop is complete.

WORKING COPY

+4
source share
2 answers

This is because JavaScript is executed in a asyncmanner. When I console.log(i)executed, I for loopcompleted my iteration, and since JavaScript does not have a block level area, the value iin console.log(i)became 3for all iterations.

The workaround for this is to use IIFE and pass iinto scope:

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

  })(i);
}
Run codeHide result

Learn more about IIFE

+8

, setTimeout() timer.so, , . .

JSConf ,

0

Source: https://habr.com/ru/post/1621069/


All Articles