Jason Stallard
Jason Stallard

Reputation: 348

javascript for loop not ending

I am trying to do a for loop in javascript with a variable to specify the increment. The following function uses the previous value (oldVal) of a DIV and the value that it has been changed to (newVal) to change a total (curtot) shown in another DIV.

 function spinctrltotaling(sender, newVal) {
        var curtot = Number(document.getElementById("totaling").innerHTML);
        console.log(curtot);
        var transtot = 0;
        var ld = "";
        var oldVal = sender.GetOldValue();
        console.log(oldVal);
        if (newVal - oldVal >= 0) {
            ld = "i=i+1";
        } else {
            ld = "i=i-1";
        }
        ;
        console.log(ld);
        for (i = oldVal; i <= newVal; ld) {
            console.log(i);
            if (i <= 0 & ld == "i=i+1") {
                transtot = transtot - (i + 1);
                console.log("i <= 0");
            } else if (i < 0 & ld == "i=i+1") {
                transtot = transtot + i;
                console.log("i < 0");
            } else if (i >= 0 & ld == "i=i+1") {
                transtot = transtot - (i - 1);
                console.log("i >= 0");
            } else {
                transtot = transtot + i;
                console.log("else");
            }
        }
        ;
        if (curtot - transtot < 0) {
            sender.SetCurrentValue = oldVal;
        } else {
            document.getElementById("totaling").innerHTML = transtot;
            document.getElementById("debuging").innerHTML = "curtot=" + curtot
                    + "    oldVal=" + oldVal + "    newVal=" + newVal
                    + "    transtot=" + transtot;
        }
        ;
}

Console results:

0
0
"i=i+1"
0
"i <= 0"
1
"i >= 0"

There are two issues:

  1. The IF ELSE shows three of the four possible results in console instead of the one I was expecting.
  2. The loop does not end even though it should have only looped once.

I know I have made a stupid mistake but just cannot see it.

Upvotes: 1

Views: 2229

Answers (2)

fullmeriffic
fullmeriffic

Reputation: 246

You need to know whether you want to increment or decrement the iterator in your for loop. Then, you need to do that. So, something like:

if (newVal - oldVal >= 0) {
   for (i = oldVal; i <= newVal; i++) {
        ...
   }
} else { 
     for (i = oldVal; i >= newVal; i--) {
        ...
      }
 };

No need to mess around with "ld".

Upvotes: 1

MarcoS
MarcoS

Reputation: 17711

1) Please solve issue 2 as stated below, then remake your tests... :-)

2) The reason why the loop does not end is you do not increment loop variable i...

for (i = oldVal; i <= newVal; ld) {

should probably be:

for (i = oldVal; i <= newVal; i++) {

Upvotes: 1

Related Questions