VBScript: Functions and Loops - Do Loop
(Page 5 of 6 )
There are several types of Do Loops. They are all used when you want to execute a block of code, but don't know how many times you will want to do so. Basically, the block of code is repeated while a given condition is true or until that condition becomes true.
How to Repeat While a Condition is True
Do While Loop:
<html>
<body>
<script type="text/vbscript">
i=0
do while i < 10
document.write("Beer!" & "<br />")
i=i+1
loop
</script>
</body>
</html>
The above code will continue to loop while the value of "i" is less than 10. Each time through the loop it prints out the delicious word "Beer" and adds one to the counter variable. Note that if the value of "i" had been 9 or greater, the code would never have executed.
If you wanted to ensure that the code executed AT LEAST once, even if the value of "i" was ten, you could also do this:
<html>
<body>
<script type="text/vbscript">
i=10
do
document.write("Beer!" & "<br />")
i=i+1
loop while i < 10
</script>
</body>
</html>
Which would result in:
Beer!
Next: Do Until >>
More BrainDump Articles
More By James Payne