Reputation: 1459
I have the following JSFiddle: http://jsfiddle.net/uX8ZQ/
Basically I am trying to achieve a continuing for loop
until a variable gets to a certain number, loading 5 at a time. This is what I have so far:
HTML:
<button onclick="go()">Load</button>
<p id="demo"></p>
JavaScript:
var max=16;
var y=5;
function go(){
var x="";
for (var i=1;i<=y;i++){
if(i>max){
return;
}
x=x + "The count is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
y=y+5;
}
The result I get is the loop stops at 15
and won't load 16
I am new to JavaScript and trying to learn my way through loops but this one I cannot seem to get.
By the way, in the JSFiddle I have used window.go = function(){
as JSFiddle will not work by simply defining the function. I am using the above code in my document.
Upvotes: 0
Views: 1865
Reputation: 5578
Use break
instead of return
as return
will exit the function before it gets to update the HTML.
function go(){
var x="";
for (var i=1;i<=y;i++){
if(i>max){
break;
}
x=x + "The count is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
y=y+5;
}
Upvotes: 3