开发者

Javascript empty loop

I saw some code like this:

while(aj开发者_如何学CaxCallInProgress)
        {
        }
        ajaxCallInProgress = true;

What is the use of this empty loop in javascript? What its does ? Thanks in advance...


if ajaxCallInProgress is a truthy expression, this will be an infinity-loop (and therefore, will freeze the interpreter forever).

It makes sense in a lot of places to do something, while a specific condition is true, but in all of those cases, the condition which is checked must set to a falsy value at some point within the loop body.

Since ECMA-/Javascript doesn't support multiple threads (I Just ignore web-workers here), there is no way this variable could get modified somewhere else.

Conclusion:

whereever you saw this code you either didn't copy & paste it completely or the author of this code didn't really know what he is doing.


It loops endlessly until ajaxCallinProgress becomes false. While it loops it's eating as much CPU as one thread can.

I think this is a very bad example of performing a blocking operation, a better way to handle something that is asynchronous would be with events.

Hope this helped.


It looks like it's locking code to prevent more than one AJAX call happening at once. Basically, if ajaxCallInProgress is true then it waits until it's been set to false by a completion callback somewhere and then sets it to true itself so it can make its own call. Not an ideal approach, queueing the calls would make more sense, but that's what it's doing.


The code is creating a spinlock. This code will spin around and around doing nothing while it waits for an event handler to change the value of ajaxCallInProgress. Presumably an Ajax request has been sent off to a server and this code is waiting for the response to come back and for the event handler waiting for that response to change the value of ajaxCallInProgress, after which this code will continue on.


if ajaxCallInProgress is true then it will do an infinite loop. Javascript is single threaded so the value will never change inside the loop. You want to use a callback function to know when the ajax call is finished.

What you want is something like this:

$.get('url', {params: true}, function success (data){ /*this will run when the ajax call finishes */});


This code seems to wait the response of an ajax call. Basically, this loop waits until the global variable ajaxCallInProgress is set to false by another JavaScript function.

So when the response is received, the corresponding JavaScript function will set ajaxCallInProgress = false;, and your loop will stop.


If the "ajaxCallInProgress" is true at the beginning and the script isn't run async it would hang your browser.

If it's run async it would consume alot of CPU but the browser wouldn't hang.. hard to tell anything more from that code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜