문제

좋아, 그래서이 코드가 있습니다.

$(this).find('article.loading').each( function(i) {

    var el = this;
        setTimeout(function () {
        $(el).replaceWith($('#dumpster article:first'));
    }, speed);

});

각 요소를 다른 요소로 바꾸고 싶지만 각 교체 사이의 지연을 원합니다.

이것이 왜 작동하지 않는지 알 수는 없습니다. 한 번의 타임 아웃 후에는 모두 대체됩니다.

어떤 아이디어?

감사.

도움이 되었습니까?

해결책

요소를 반복하고 동일한 구성으로 각각에 타이머를 추가합니다. 본질적으로 각 요소마다 새 타이머가 즉시 설정됩니다. 모든 타이머의 첫 번째 진드기에서 요소가 업데이트됩니다. 간격은 각각에 대해 동일하므로 모두 동시에 업데이트되는 것처럼 보입니다.

논리는 타이머를 중심으로해야합니다. 타이머의 각 진드기는 컬렉션의 다음 요소를 업데이트해야합니다. 각 루프가 필요하지 않으며, 마지막 요소를 업데이트 한 후에 타이머를 중지하면서 증분 인덱스와 결합 된 타이머를 사용하여 타이머를 중지하십시오.

var elements = $(this).find('article.loading');
var index = 0;

setTimeout(function () {
    $(elements).get(index).replaceWith($('#dumpster article:first'));
    index++;
}, speed);

위와 같은 것이 있지만 타이머를 멈추는 것을 잊지 마십시오!

다른 팁

나는 당신의 코드를 수정하고 약간의 변경을합니다. 약간의 속임수.

$(this).find('article.loading').each( function(k, v) {
    var el = this;
        setTimeout(function () {
        $(el).replaceWith($('#dumpster article:first'));
    }, k*speed);
});

Andy McCluggage가 어떻게 작성되었는지 정확히 알 수 있습니다. 나는 이런 것이 당신을 도울 수 있다고 생각합니다.

var speed = 1000;

// init timer and stores it's identifier so it can be unset later
var timer = setInterval(replaceArticle, speed);

var articles =  $('article.loading');
var length = articles.length;

var index = 0;
function replaceArticle() {
     articles.eq(index).replaceWith($('#dumpster article:first'));

     index++;

     // remove timer after interating through all articles
     if (index >= length) {
         clearInterval(timer);
     }
}

함께 시도하십시오 window.setTimeout.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top