0

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.

1
  • 3
    return exits the function. Did you mean break? Commented Mar 18, 2014 at 10:47

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.