0

I am counting values from 0 to 100 in JavaScript, but the whole count should take 3 seconds to reach 0 to 100.but right now its happening withing milliseconds.

how can i do that?

<span><span id="counter"> </span> of 100 files</span> <script> for(var i=0;i<=100;i++) { setTimeout(document.getElementById("counter").innerHTML = i, 3000); } </script> 

Example:

http://www.downgraf.com/wp-content/uploads/2014/09/03-yodaloader.gif

12
  • Why are you setting a ton of intervals Commented Sep 22, 2016 at 4:51
  • @AndrewL.opps that was wrong line of code, it was suppose to be setTimeout in my code. just changed it Commented Sep 22, 2016 at 4:54
  • So what's wrong with the code? Commented Sep 22, 2016 at 4:56
  • @AndrewL. what i want to achieve is the loop should count from 0 to 1 like 0 1 2 3.. and so on till 100, the whole count should take 3 seconds. But now the count is happening within milliseconds its not counting like how i want to. Commented Sep 22, 2016 at 4:57
  • ok you want to print 0 to 100 with animation right Commented Sep 22, 2016 at 4:59

1 Answer 1

4

I'm guessing you mean to go from 1 - 100 in 3 seconds, here's an example:

var i = 0; var inv = setInterval(function() { if(i < 100) document.getElementById("counter").innerHTML = ++i; else clearInterval(inv); }, 3000 / 100); 

This makes the whole incrementation take about 3 seconds. It's achieved by setting an interval that (prefix) increments global variable i and sets as innerHTML every 0.03 seconds. It then clears the interval after reaching 100. You can modify step, speed, and bounds to your liking. Here's an example on JSFiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

@MithunRaikar no problem :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.