如何使用超时功能进行无限循环

时间:2015-01-23 09:23:30

标签: javascript jquery html

如何使用超时功能在无限循环中创建此计数器。这是我的代码。任何帮助高度赞赏。

JS Fiddle

HTML

<div class="counter inner">
        <ul>
          <li>
              <h5 class="count">35</h5>
              <p>Years</p>
          </li>
          <li>
              <h5 class="count">150</h5>
              <p>Employees</p>
          </li>
        </ul>
    </div>

JS

$('.count').each(function () {
$(this).prop('Counter',0).animate({
    Counter: $(this).text()
}, {
    duration: 2000,
    easing: 'swing',
    step: function (now) {
        $(this).text(Math.ceil(now));
    }
});
});

JS Fiddle

2 个答案:

答案 0 :(得分:6)

$('.count').each(function () {
    (function rec(self, cnt) {
        $(self).prop('Counter',0).animate({
            Counter: cnt
        }, {
            duration: 2000,
            easing: 'swing',
            step: function (now) {
                $(self).text(Math.ceil(now));
            },
            complete : function() {
                setTimeout(function() {
                    rec(self, cnt);
                }, 400);
            }
        });
    }(this, $(this).text()));
});

FIDDLE

答案 1 :(得分:1)

使用完整的回调,重置计数器,然后再次调用动画。

$('.count').each(function anim() {
$(this).prop('Counter',0).animate({
    Counter: $(this).text()
}, {
    duration: 2000,
    easing: 'swing',
    step: function (now) {
        $(this).text(Math.ceil(now));
    },
    complete: function(){
        $(this).css('counter',0);
        setTimeout(anim.bind(this),1000);
    }
});
});

Fiddle

相关问题