1

the following code is just to test the functionality

for (var i = 1; i <= 5; i++) {

  if(i==4){
    console.log(document.getElementById("loading").classList.contains("invisible"));
    break;
  }else{
    (function(i){ 
    setTimeout(function() { console.log(i) }, i*1000);
    })(i);
  }
  
}
/*this basically gives true or false as result
document.getElementById("loading").classList.contains("invisible")*/

this is the console log

false
1
2
3

Now my question is how & why am I getting false even if the if condition "(1==4)" is not true and why doesn't the code break when the first part of if statement is executed to get false

morganbaz
  • 2,997
  • 1
  • 17
  • 30

1 Answers1

0

The anonymous callback function passed to setTimeout is invoked asynchronously. Hence, it may be the case that the console.log for i==4 is evaluated before the other console.log is evaluated.

jboockmann
  • 1,011
  • 2
  • 11
  • 27