bean
bean

Reputation: 337

How to make a modified counter animation in JavaScript?

I need to create a web page that shows two buttons: "Start" and "Stop". When "Start" is clicked, I need to display an equation every second. For example:

Suppose that the starting number is 100, then in the animation, the web page will first display:

100 + 1 = 101

And then every second after that, it should display:

100 + 2 = 102; 
100 + 3 = 103;
100 + 4 = 104; 

and so on...every 1 second.

I have been able to create the counter animation, however, I am stuck as to how to progress after this.

Here is my code so far

<html>
<head>
  <script>

  var counter = 100;
  var counterSchedule;

  function startCounterAnimation(){

    counterSchedule = setInterval(showCounter, 1000);
  }

  function showCounter(){

    counter = counter + 1;

    var counterSpan = document.getElementById("counter");
    counterSpan.innerHTML = counter;
  }

  function stopCounterAnimation(){

    clearInterval(counterSchedule);
  }

  </script>
</head>
<body>

  <button onClick="startCounterAnimation()">Start Animation</button>
  <button onClick="stopCounterAnimation()">Stop Animation</button>

  <br /><br />

  <span id="counter"></span>
</body>
</html>

Any help would be greatly appreciated!

Upvotes: 1

Views: 134

Answers (1)

Tyler
Tyler

Reputation: 616

Try out with the code below. Is that what you're looking for?

  var counter = 100;
  var counterSchedule;
  let i = 1;

  function startCounterAnimation(){

    counterSchedule = setInterval(showCounter, 1000);
  }

  function showCounter(){

    counter = counter + 1;
    var counterSpan = document.getElementById("counter");
    counterSpan.innerHTML = `100 + ${i} = ${counter}`;
    i++;
  }

  function stopCounterAnimation(){

    clearInterval(counterSchedule);
  }
<html>
<head>
</head>
<body>
  <button onClick="startCounterAnimation()">Start Animation</button>
  <button onClick="stopCounterAnimation()">Stop Animation</button>

  <br /><br />

  <span id="counter"></span>
</body>
</html>

Upvotes: 2

Related Questions