Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61529

Javascript when callback will be called, and will it?

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; 
}

Upvotes: 0

Views: 51

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173662

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".

Upvotes: 2

Related Questions