Question

Let's consider following situation:
I have a function (Function1) that calls another function (Function2) and passes callback function (Function3) in.
Then it has infinite loop immediately after, to escape from which mechanism lies in callback, will callback function ever be called? How to reach console.log('reached here');?

var IamTrue = true;
function Function1() {
   Function2(Function3);
   while(IamTrue){ }
   console.log('reached here');
} 

function Function2(f3) {
   setTimeout(f3, 500);
}

function Function3() { 
   IamTrue = false; 
}
Was it helpful?

Solution

JavaScript uses a single threaded run loop to execute your code; the moment your code returns it can schedule things like event handling, delayed code execution, AJAX responses, etc.

However, the code in Function1 never ends, so the JavaScript engine never gets a chance to schedule the execution of Function2 and thus "nothing happens".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top