0

I have this js snippet,

let checker={flag:0,dirtyFlag:false};

let i=0;

setTimeout(()=>{
  console.log('value of checker updated');
  checker.dirtyFlag=true;
  checker.flag=1;
},2000)

while (true) {
  console.log(i++);
  if(checker.flag==1){
    console.log(checker.dirtyFlag);
    break;
  }
}

but the code runs endless, whereas expected behavior is, it should stop after 2000ms.

how can i debug the above code.

shubh kr
  • 21
  • 6
  • `while (true) { ... }` blocks the process from doing anything else. – Andreas Nov 04 '20 at 10:55
  • What are you trying to achieve with this script? – Andreas Nov 04 '20 at 10:56
  • @Andreas, i have used setTimeout here as a mockup of observable in angular. i needed to return a value, when data comes into observable. so thought of applying it this way. but this didn't worked as expected. – shubh kr Nov 05 '20 at 04:08

1 Answers1

0

The function that setTimeout calls is added to the call stack when the main call stack runs and completes. So, it will always run after the while loop (in your case it won't complete because you are in an endless loop)

You can see an example in the below image which shows how WEB API and Callback Queue works.

enter image description here

Ozgur Sar
  • 2,067
  • 2
  • 11
  • 23