setTimeout inside $.each()

前端 未结 4 1809
借酒劲吻你
借酒劲吻你 2021-02-07 13:02

ok, so I\'ve got this code:

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

    var el = this;
        setTimeout(function () {
        $(el).replaceWith(         


        
4条回答
  •  [愿得一人]
    2021-02-07 13:49

    You are looping through the elements and adding a timer to each with the same configuration. Essentially a new timer is instantly set up for each element. On the first tick of all the timers the elements are updated. The interval is the same for each so they all appear to update at the same time.

    Your logic needs to be centred around the timer. Each tick of the timer needs to update the next element in the collection. You don't need an each loop, use the timer combined with an incremented index as your looping mechanism, stopping the timer once you have updated the last element.

    var elements = $(this).find('article.loading');
    var index = 0;
    
    setTimeout(function () {
        $(elements).get(index).replaceWith($('#dumpster article:first'));
        index++;
    }, speed);
    

    Something like above, but remember to also stop the timer!

提交回复
热议问题