The While Loop is used to execute a block of statements till specified condition is true, if the condition becomes false the While Loop terminates. This is the very basic loop in JavaScript.
<script> function TestFunction() { var i = 0; while (i < 5) { alert(i); i++; } } </script> <input type="button" id="btnTest" onclick="TestFunction()" value="Click me" />
In above code snippet, on click of button TestFunction() shall fire that will run a while loop. That loop executes five times and gives alert messages from 0 to 4.
NOTE: Make sure that you are incrementing/decrementing (as the case may be) the value you are going to test, otherwise an indefinite loop begins that may stuck your browser.
<p>Click the button to show the result.</p> <input type="button" value="Button" onclick="myLoop()"/> <p id="myId"></p> <script> function myLoop() { var text = ""; var i = 0; while (i < 6) { text += "<br>This is " + i; i++; } document.getElementById("myId").innerHTML = text; } </script>
We are returning the 6 lines of output with a single code by using JavaScrip While loop.
OUTPUT
Views: 5690 | Post Order: 27