iniestar
iniestar

Reputation: 262

Array not being populated in some ocasions

I'm having a hard time to crack this one out, would appreciate a hand with this script.

Trying to do a countdown script where I have to display the new number counting from previous.

let oldN = 0;
let newN = 0;
let arr = [];

function runner() {
  arr = [];
  newN = document.getElementById('newVar').value;

  console.log("stored: " + oldN + " new: " + newN);

  if (oldN > newN) {
    for (let i = oldN; i >= newN; i--) {
      arr.push(i);
    }
  } else if (oldN < newN) {
    for (let e = oldN; e <= newN; e++) {
      arr.push(e);
    }
  }

  console.log("array: " + arr.length);
  oldN = newN;

  for (let u = 0; u < arr.length; u++) {
    (function(index) {
      setTimeout(() => {
        document.getElementsByTagName('span')[0].innerText = arr[index];
      }, 100 * u);
    })(u);
  }

}
<div class="board">
  <span><!----></span>
</div>

<br/>
<input type="text" id="newVar" />
<button onclick="runner()">Start</button>

It seems to work but if I go from 13 to 7 it won't populate the array thus not running the countdown, the same issue happens when going from 7 to 13.

Any idea?

Kind Regards

Upvotes: 0

Views: 64

Answers (1)

Bergi
Bergi

Reputation: 664548

You forgot to convert the input value (a string) to a number. They are compared alphabetically not numerically then, and "13" < "7" so your loop doesn't work. Use

newN = parseInt(document.getElementById('newVar').value, 10);

Upvotes: 4

Related Questions