0

I've reviewed the other clearInterval posts here for a clue as to why my code isn't functioning as intended. Despite my best efforts, I still can't get clearInterval to stop my count.

I'm trying to do something simple: have a count, increase by one until the stop button is pushed.

I have tried different, and incorrect variables, but I cannot find a working solution.

    <p>Count Up:</p>
    <p id="count">1</p>
    <button onclick="clearInterval(current)">Stop</button>
    <script>
      var current = 1;
      function animateValue(id) {
        var obj = document.getElementById(id);
        var current = parseInt(obj.innerHTML);
        setInterval(function () {
          current++;
          obj.innerHTML = current;
        }, 1000);
      }
      animateValue("count");
    </script>
bguiz
  • 27,371
  • 47
  • 154
  • 243
  • 1
    Have you read the [documentation](//developer.mozilla.org/docs/Web/API/clearInterval)? That would be a good start for “best efforts”. Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Nov 01 '21 at 02:44
  • 1
    You need to pass the return value of `setInterval` into `clearInterval` and not some arbitrary number. – CherryDT Nov 01 '21 at 02:45
  • @SebastianSimon—I think the OP is just an example. For that it's just fine. :-) – RobG Nov 01 '21 at 03:11

1 Answers1

3

Store the value returned by setInterval in a variable and pass that as the parameter to clearInterval instead of counter:

<p>Count Up:</p>
<p id="count">1</p>
<button onclick="clearInterval(interval)">Stop</button>
<script>
  var interval;
  var current = 1;
  function animateValue(id) {
    var obj = document.getElementById(id);
    var current = parseInt(obj.innerHTML);
    interval = setInterval(function () {
      current++;
      obj.innerHTML = current;
    }, 1000);
  }
  animateValue("count");
</script>
Spectric
  • 30,714
  • 6
  • 20
  • 43