|
|

tips menu | printable single page versionNote: this
is my old ASP tips page and is no longer supported. See the new Visualize web site..
ASP Coding and Style - exiting loops
When looping in ASP, it makes sense to avoid looping more times than is necessary and exit the loop as soon as you can. This can normally be accomplished by having appropriate conditions on the loop itself, for example:
dim i
i=0
do while i < 10 and not rs.eof
' process your recordset here...
rs.movenext
i = i + 1
loop
Occasionally, it is sometimes useful to exit a loop early, even if the main loop conditions are not met. VBscript offers the Exit For and Exit Do statements for just this purpose. For example, if we wanted to add some code which exits the loop if some error arises, then we could write this as follows:
i=0
do while i < 10 and not rs.eof
' process your recordset here...
If [some error occured] then
Exit Do
end if
rs.movenext
i = i + 1
loop
Generally, it is good coding practice to put the conditions on the loops themselves, as opposed to using the exit statements illustrated above. However, the exit statement is extremely useful for exiting if a special case arises. This avoids the need to have extra boolean flags etc.
DISCLAIMER: Note these pages are a free resource for anyone wishing to reference them. Although every care is taken to ensure their correctness, the author takes no responsibility for any errors or problems that may occur through their use, or indeed misuse. These pages are copyight of Dave Clarke, Visualize Software Ltd 1997-2000 (all rights reserved).
© Copyright
Dave Clarke, 1996-2010
|