user2116245
user2116245

Reputation:

How to end my for loop?

I need to end a for loop in Javascript.. obvious answer is while loop - however I'm not sure how to implement it here, I tried putting while on the front of the for loop (while(stop==false)), but then it lasts forever...

The function this code is in is performed every 1 millisecond. At the moment, even if stop == true it goes through the rest of the divs.. How do I make it that if stop == true, don't carry on looking through them.

<script>
    for (var i = 1; i <= gDivCount; i++) {

        var topleftofgdiv = [$("#" + i).position().top, $("#" + i).position().left];
        var toprightofgdiv = [$("#" + i).position().top,
        $("#" + i).position().left + $("#" + i).width()];

        if (topleftofgdiv[0] > bottomleft[0]) {
            var stop = false;
            console.log(false);
        } else {
            var stop = true;
            console.log(true);
        }

        if (stop == false) {
            var pandanewpos = $("#moveDiv").position().top + 3;
            document.getElementById("moveDiv").style.top = pandanewpos + "px";
        }
    }
</script>

Upvotes: 1

Views: 1955

Answers (1)

George Cummins
George Cummins

Reputation: 28906

Use break:

if(stop){
    break;
}

For simplicity, you can use your existing if statement:

if (stop == false) {
    var pandanewpos...
}
else {
    break;
}

Upvotes: 3

Related Questions