Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript empty loop

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

like image 426
Aneesh Avatar asked Feb 11 '11 12:02

Aneesh


People also ask

How do you write empty in JavaScript?

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.

Can you have an empty while loop?

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.

How do you make an infinite loop in JavaScript?

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.

What is nothing in JavaScript?

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.


2 Answers

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.

like image 160
jAndy Avatar answered Oct 08 '22 10:10

jAndy


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.

like image 33
Kevin Avatar answered Oct 08 '22 11:10

Kevin