973-584-9100 bgl@bardess.com

Most loops you will see are For loops. These are great if you can programmatically determine the number of loops you need to do. For example the number of rows of a table. However, what if you need to loop as long as it takes to finish? You don’t know how long it will take. Say you want to extract from an unreliable database that fails for unspecified reasons and you just have to try until you succeed. These type of examples are where Do While loops come in.

Do..Loop, or as I like to call it “Do While”, allows you to loop until a condition is met.

In this example, I want to loop for 5 seconds give or take.

do while


Which returns:

do while

12,108 iterations in 5 seconds, so 2,481 a second. That’s pretty fast! Granted I wasn’t doing any heavy lifting, but still.

While this example isn’t exactly practical, I think it shows the point. If you are interested in a more realistic use case, check out my article on Queing.