HTML and CSS Reference
In-Depth Information
The expression is something that evaluates to a Boolean. While the expression is
true
, the
while
loop continues to run. The code that runs is contained within the code block inside the
braces. The condition must be
true
for the
while
loop to run at all. Because the
while
loop
doesn't use an incrementer like the
for
loop
does, the code inside the
while
loop must be able
to set the expression to
false
as appropriate; otherwise, the loop will be an endless loop. You
might actually want to use an endless loop, but you must ensure that the processing of the
loop doesn't block the application's main thread. The following code demonstrates a
while
loop:
var i = 0;
while (i < 10) {
//do some work here.
i++;
}
In this code, the
while
loop runs until the variable
i
equals 10. The expression can hold just
about anything as long as it evaluates to a Boolean.
The preceding example is fairly deterministic in that you know the loop will run 10 times.
However, in some situations a block of code should run until something else changes that
could be outside the loop's control. Suppose that an application is moving traffic through an
intersection. This type of application could move traffic as long as the traffic signal is green.
The following code demonstrates this:
var canvas = document.getElementById("canvas1");
while (canvas.styles.backgroundColor == 'green') {
//move traffic
}
This
while
loop will never end until the canvas background is no longer green. The loop
depends on logic elsewhere in the application to change the background color of the canvas,
such as a timer that controls how long the traffic signal stays green or red.
One other form of the
while
loop is the
do…while
loop.
Using the
do…while
loop
The key difference between the
while
loop and the
do…while
loop is that
do…while
always
runs at least the first time. In contrast, the
while
loop first evaluates the expression to
determine whether it should run at all, and then continues to run as long as the expres-
sion evaluates to
true
. The
do…while
loop always runs once because in this form of loop,
the expression logic is at the bottom. The
do…while
loop achieves this with the following
structure:
do{
<
code block
>
}while(<
expression
>)
Search WWH ::
Custom Search