Animated counter doesn't animate at all - Javascript

I have the following JavaScript animation:

window.onload = function() {
    // should return a number like 100
    var total = parseInt(document.getElementById('foo').className);
    function showBars(bars) {
        document.getElementById("bar").innerHTML = bars + " bars";
        if (bars < total) {
            setTimeout(showBars(bars + 1), 20);
        }
    }
    console.log(total);
    if (total > 0) showBars(0);
}

      

HTML:

<span id="foo" class="100" />
<p id='bar' class='100'>100 Bars</p>

      

So, instead of having the desired effect of incrementing the bars one by one (visible to the user), I just see the number sent by ( 100

). I know the problem is window.onload

, but how can I replace with window.onload

another event that will produce the result I'm looking for?

+3


source to share


1 answer


Probably the main problem here:

setTimeout(showBars(bars + 1), 20);

      

This code calls a function showBars

and then passes its return value to setTimeout

, just like it foo(bar())

calls bar

and passes its return value to foo

.

If you replace it with

setTimeout(showBars.bind(null, bars + 1), 20);

      



... it will pass a function setTimeout

that, when called, will call showBars

c bars + 1

as an argument.

Live example: (I also removed both attributes class

with classes starting with numbers, replacing one with foo

with data-max

as discussed in the comments)

window.onload = function() {
    // should return a number like 100
    var total = parseInt(document.getElementById('foo').getAttribute("data-max"));
    function showBars(bars) {
        document.getElementById("bar").innerHTML = bars + " bars";
        if (bars < total) {
            setTimeout(showBars.bind(null, bars + 1), 20);
        }
    }
    if (total > 0) showBars(0);
};
      

<span id="foo" data-max="180" />
<p id='bar'>100 Bars</p>
      

Run codeHide result


+4


source







All Articles