3

So I have this simple HTML:

<span id="badge">0</span>

I want the number 0 to increase by 1 every x milliseconds. How do I do that with Javascript (with or without jQuery)?

Thanks a bunch - I'm new to this :)

ponjoh
  • 927
  • 3
  • 9
  • 9
  • Check this page for a better choice between setInterval and setTimeout: http://stackoverflow.com/questions/729921/settimeout-or-setinterval – Ricardo Souza Mar 22 '12 at 15:45

8 Answers8

2

You should do this:

<script>
   var $badge = $('#badge'); // cache 
   setInterval(function () {
        var value = parseInt($badge.html());
        value++;
        $badge.html(value);
   }, 1000);

</script>

Assuming 1000 milliseconds.

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
Richard
  • 21,728
  • 13
  • 62
  • 101
  • 1
    Uh, are you crazy? Executing jQuery two times each loop? Imagine an interval of 100 ms! – Bergi Mar 22 '12 at 15:59
  • Thanks! Works perfectly. If I want to add a delay to that, how can that be done? Only once, before it starts increasing the value. – ponjoh Mar 22 '12 at 16:05
1

Something like this?

var millisecs = 10;
setInterval(function() {
  var $badge = $('#badge');
  $badge.text(parseInt($badge.text())++);
}, millisecs);

http://jsfiddle.net/iambriansreed/MPP8n/3/

iambriansreed
  • 21,935
  • 6
  • 63
  • 79
jlb
  • 19,090
  • 8
  • 34
  • 65
1
function increment() {
    document.getElementById("badge").value = Number(document.getElementById("badge").value) + 1;
    setTimeout("increment()",3000);
}
increment()
Tom
  • 4,096
  • 2
  • 24
  • 38
1

Every of the answers I see here has the same drawbacks:

  • performance issue because of selecting the DOM element every ms cycle. Especially when using a heavy library as jQuery.
  • setInterval() is probably the tool designed for that functionality, but not reliable. It can diverge a lot from the real time, especially when using a small interval. If you want exactly x executions per second, you may google for some timing libraries.

I would code:

var textNode = document.getElementById(badge).firstChild;
var start = Date.now();
window.setInterval(function update() {
    textNode.data = Math.round((new Date()-start)/ms);
}, ms);

If you don't want to start at 0, it will be trivial to add an offset (determined before the loop begins), eg.

var start = Date.now() - (textNode.data * ms || 0); // NaN catching, implicit number cast
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

You could create a Jquery plugin, so you can reuse whenever you need.

$.fn.increment= function(options) {

 var $this = $(this);

 var coef = options.coef;

 var speed = options.speed;

 var value = 0;

 setInterval(function(){ 

    value = value + coef ;

    $this.html(value);

 }, speed);

};

And in your main javascript file :

$("#badge").increment({coef: 1, speed:1000});

working demo : http://jsfiddle.net/8FMZh/102/

0

Check this http://www.w3schools.com/js/js_timing.asp

pollirrata
  • 5,188
  • 2
  • 32
  • 50
0

You can use setInterval.

var $badge = $('#badge');
setInterval(function () {
     $badge.html(parseInt($badge.html()) + 1);
}, 1);​//Specify the milliseconds here, right it will update the value every 1 millisecond

Working demo - http://jsfiddle.net/8FMZh/

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

A little more about timers:

// setting a variable for your timer will allow you the ability to "turn it on and off"
var tmrChangeI;
// setTimeout is a function to initiate a function once after given amount of milisecs
// whereas setInterval will continue a function until cancled every so many milisecs

// the following wil "turn on" your timer
tmrChangeI = setInterval(function() {
    var $badge = $('#badge');
    $badge.html($badge.html() + 1);
}, 500); // 500 will = every half of a second

// to "turn off" timer
clearInterval(tmrChangeI);

// or set a bool to test and use timeout to repeat till bool is false
var tmrBool = true;

// establish function to execute
function tmrFunc() {
    var $badge = $('#badge');
    $badge.html($badge.html() + 1);
    if (tmrBool) tmrChangeI = setTimeout(function() { tmrFunc(); }, 500); // 500 will = every half of a second
};

// execute function, begin timer
tmrChangeI = setTimeout(function() { tmrFunc(); }, 500);

// clear via bool allowing one more execution
tmrBool = false;

// clear by force possibly stoping next execution,
// tho in this manner it may be too late if timer is very short 
// and maybe overriden by bool still being true, this is not safest 
// but is example of how to use setTimeout
clearTimeout(tmrChangeI);
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81