0

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

mpm
  • 20,148
  • 7
  • 50
  • 55
iniestar
  • 262
  • 2
  • 5
  • 14
  • 6
    Side note: Your code seems to be falling prey to what I call [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html). declare your variables. It may or may not be *the* problem, but it is **a** problem. – T.J. Crowder Sep 10 '18 at 12:23

1 Answers1

4

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 3
    @ iniestar - You have lots of options for how to convert from string to number; [my answer here](https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875) describes them. – T.J. Crowder Sep 10 '18 at 12:32
  • Thank you guys, completely forgot about type checking. – iniestar Sep 10 '18 at 12:41