I saw some code like this:
while(ajaxCallInProgress)
{
}
ajaxCallInProgress = true;
What is the use of this empty loop in javascript? What its does ? Thanks in advance...
The empty statement is a semicolon ( ; ) indicating that no statement will be executed, even if JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one.
Syntax and example of empty while loop in JavaBecause it is an empty while loop java, it will not return anything when we run the code. Such a loop is a time delay loop. The time delay loop is useful for pausing the program for some time.
Let us see some examples of how we can run into infinite loops. One of the most common infinite loops is when the condition of the while statement is set to true. Below is an example of code that will run forever. Another classic example will be of the for loop where the terminating condition is set to infinity.
JavaScript has two values which mean "nothing", undefined and null . undefined has a much stronger "nothing" meaning than null because it is the default value of every variable. No variable can be null unless it is set to null , but variables are undefined by default.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With