문제

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; 
}
도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top