简体   繁体   中英

How to make a counting animation in JavaScript?

Ok, so I have to display a text field so that the user can enter an integer. Then display two buttons “Start Animation” and “Stop Animation”.

When the button “Start Animation” is clicked, the web page displays an animated times table in the following manner.

For example, if the user entered the number 6, then the animation displays

6 x 1 = 6, one second later it replaces it with 6 x 2 = 12, one second later it replaces it with 6 x 3 = 18, etc. If it is 6 x 9 = 54, then one second later it becomes 6 x 1 = 6, and then 6 x 2 = 12, and so on.

When the button “Stop Animation” is clicked, then the web page stops the animation. Whatever the equation is currently displayed will stay there on the page.

Here is the code I have so far.

 var counter = 0; var counterSchedule; function startCounterAnimation() { // start the counter animation counterSchedule = setInterval(showCounter, 1000); } function showCounter() { // increase the counter by 1 counter = counter + 1; // show the counter var counterSpan = document.getElementById("counter"); counterSpan.innerHTML = counter; } function stopCounterAnimation() { clearInterval(counterSchedule); } 
 <input id="number" type="text"> <button onclick="startCounterAnimation()">Start Animation</button> <button onclick="stopCounterAnimation()">Stop Animation</button> <br/><br/> <span id="counter"></span> 

I don't understand exactly what you wanted help with but I fixed it according to what i understood

 var counter = 0; var counterSchedule; var input = document.getElementById("number"); var counterSpan = document.getElementById("counter"); function startCounterAnimation() { counterSchedule = setInterval(showCounter, 1000); } function showCounter() { if (~~input.value) { if (counter >= 10) counter = 0; counter++; counterSpan.innerHTML = input.value + " X " + counter + " = " + eval(input.value + " * " + counter); } } function stopCounterAnimation() { clearInterval(counterSchedule); input.value = ""; counter = 0; } 
 <input onClick="stopCounterAnimation()" id="number" type="text"> <button onclick="startCounterAnimation()">Start Animation</button> <button onclick="stopCounterAnimation()">Stop Animation</button> <br/><br/> <span id="counter"></span> 

I am not sure if I understand your question (I don't really see a question) correctly. Your code looks fine but you want it to start over again once it reaches 10? Try using the modulo operator % So replace

counterSpan.innerHTML = counter;

With

counterSpan.innerHTML = counter % 10;

Tell me if I misunderstood the question or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM