-1

I would like a counter. The starting number will be:

10,000,000

Every 6 seconds, it will add 1, so it will be: 10,000,001 and then 10,000,002 and so on...

I would like to able to style the number: font-family, color, font-size, etc.

Can some please help me?

user2343800
  • 133
  • 1
  • 4
  • 16

2 Answers2

0

jQuery includes a function called setTimeout(), which causes a function to be called after a set time-delay. Something like the following would do what you are asking. Ensure that your document includes a DOM element with the id counter. Then:

var counter = 10000000;
function incrementCounter() {
   counter++;
   $('#counter').html(counter);
   setTimeout(incrementCounter, 6000);
}
setTimeout(incrementCounter, 6000);

What’s going on here? setTimeout takes two arguments: the function to be called and the time-delay in milliseconds. The final line sets the function incrementCounter(), which we defined, to run after a delay of six seconds. The function increments the counter variable, sets the DOM object’s text to the value of the counter variable, then sets the timeout again: this means that the function will run every six seconds until something stops it.

As for styling the counter, this can be done either using static CSS or with the jQuery style-manipulation functions.

Seph
  • 31
  • 3
0

You can make use of setInterval to initiate a function which would be invoked in every 6000 milliseconds.

var num = 10000000;    
setInterval(function()
  {   
    num++;
    console.log(num);
    $('div').text(num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
  },6000);

Here's an example : https://jsfiddle.net/DinoMyte/sac63azn/3/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26
  • Thank you @DinoMyte. Your code works! When I add it to my webpage, it does show first 10,000,000. And of course every 6 seconds it adds 1. Great. But when I refresh the page, it reverts back to 10,000,000. Is it possible to make your code so that it remembers where the last number was and start there? For example, if I refresh page on 10,000,009 and then refresh page or reload the page, it will stat at 10,000,009 and then start to count from there. – user2343800 Feb 12 '16 at 21:00
  • You need to put have the value saved in cache to remember the last value. – DinoMyte Feb 12 '16 at 22:34
  • @DineMyte, how do I put have the value saved in cache to remember the last value ? – user2343800 Feb 12 '16 at 23:26
  • You would typically do that on server side. If want something to persist on the client side, you can use cookies. http://stackoverflow.com/questions/1458724/how-do-i-set-unset-cookie-with-jquery – DinoMyte Feb 12 '16 at 23:28
  • I still have not figure out the persist part of this counter code yet. – user2343800 Feb 15 '16 at 17:56