Completing multiple animations at the same time

I have four .dist elements. They have different preloaded data (exactly: 57, 27, 17, 244). I want to animate an increment and I wrote this code:

$('.dist').each(function() {
    var count = parseInt($(this).text())
    var incr = 0
    var that = $(this)
    var animation_time = 500
    var interv = animation_time / count

    $(this).text('0')

    var fd = setInterval(function() {
        if (incr < count){
            incr++
            that.text(parseInt(incr))
        }
    } , interv)
    console.log(interv)
})

      

Problem: Greatest value ends 100 light-years after rest.

Console.log (straight from this code) returns:

+8.928571428571429 +18.51851851851852 +29.41176470588235 2.0491803278688523

These are the values ​​we expected, but I think that each interval has a certain delay, but I do not know how to determine and fix this delay.

I want to finish all increments from 0 to "var count" in ~ = 500ms time. I want to start all increments at the same time and finish all at the same time.

Sorry for my primitive querstion, but I started my adventure with js / jq just 6 months ago and I can't find google answer. Maybe I was in awe or something. Thanks for the help.

edit: html

<div class="info back2 border corners1">
        <span class="dist">56</span>  seriali<br>
        <span class="dist">27</span>  obejrzanych<br>
        <span class="dist">17</span>  oczekuje<br>
        <span class="dist">244</span>  sezonów<br>
</div>

      

+3


source to share


2 answers


You have two problems: first, you end up with a very small interval, and second, the calculated interval becomes float. SetInterval

can handle whole milliseconds, not fractions, so your calculation will always be off. Better to set start and end times and calculate the difference.

This is the most accurate way to do time calculations in Javascript anyway.

$('.dist').each(function() {
    var count = parseInt($(this).text());
    var incr = 0;
    var that = $(this);
    var animation_time = 500;

    $(this).text('0');
    var time_start = new Date();

    var fd = setInterval(function() {
        var time_passed = new Date() - time_start;
        if (time_passed >= animation_time) {
            clearInterval(fd);
            time_passed = animation_time;
        }
        that.text(Math.round(count*time_passed/animation_time));
    } , 10);
})

      



http://jsfiddle.net/xau91msr/

Or if you don't care about the actual timing for the animation and want browser flirting, etc. were not considered past tense, you can increase it time_passed

yourself:

http://jsfiddle.net/jevjyf3m/

+3


source


If you have a fixed number of steps and increase proportionally, then your counters will reach their goals together, also remember to clear the interval after the animation ends.

http://jsfiddle.net/rtvtdasz/10



clearInterval(fd);

      

+2


source







All Articles