在循环中调用setTimeout函数

在循环中调用setTimeout函数

我需要将类添加到span元素,但是需要一段时间。

jQuery('.rating').each(function(){
    var datarating = $(this).attr("rating");
    for(var i=0; i<datarating; i++){
        (function (i) {
         setTimeout(function () {
            rating(this, i);
         }, 1000, i);
        })(i);
    }
});

function rating(obj, i){
    $(obj).find('span').eq(i).addClass('rated');
}


HTML:

<div class="rating" rating="2">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>
<div class="rating" rating="3">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>


我做错了。我无法在循环中调用setTimeout函数在脚本结尾必须是结果。

<div class="rating" rating="2">
    <span class="rated"></span>
    <span class="rated"></span>
    <span></span>
    <span></span>
    <span></span>
</div>
<div class="rating" rating="3">
    <span class="rated"></span>
    <span class="rated"></span>
    <span class="rated"></span>
    <span></span>
    <span></span>
</div>

最佳答案

尝试这个

jQuery('.rating').each(function(){
    var rating = this;
    var datarating = $(this).attr("rating");
    var i = 0;
    var interval = setInterval(function () {
       if ( i <  datarating ) {
           rating(rating, i);
           i++;
       } else {
           clearInterval(interval);
       }
    }, 1000, i);
});

10-02 19:23