Aug

24

JavaScript Stop a Loop

August 24, 2008 |

Sometimes you may want to use a for loop to check and match something and you expect the script to stop at the point that it found the match from an array of values.

This can be simply done by inserting break in the loop. The build-in break command will break the loop and continue executing the code that follows after the loop (if any). Below is an example of how this can be done:

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i+=1)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

The example above will produce the result below:
The number is 0
The number is 1
The number is 2


It stops when i equals to three.



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links