延迟调用每个循环中的函数执行

时间:2015-08-11 11:48:16

标签: jquery

我想为数组中的每个项执行一个函数。但是我不希望所有功能同时执行。我想说它为第一个项目执行函数,然后在执行第二个元素的函数之前等待2秒。我怎么能这样做我不太确定。谢谢!

$.each(sliderArray, function(index, value) {
       console.log("array value is "+this);
       openQv(this);
   });

3 个答案:

答案 0 :(得分:0)

尝试使用setTimeout(),最重要的是不要忘记每次迭代创建一个范围,

$.each(sliderArray, function(index, value) {
    var $this = this;
    (function(i){ 
       setTimeout(function(){ openQv($this) }, i*2000) 
    })(index);
});

答案 1 :(得分:0)

setTimeout()会满足吗?

$.each(sliderArray, function(index, value) {
       var $this = index;
        setTimeout(function()
        {
          console.log("array value is " + $this);
          openQv($this);
        },2000); 
   });

答案 2 :(得分:0)

如果您希望延迟按顺序操作,您可以尝试这样的事情:

function open(items, delayBetweenItems) {
    function handleItem(itemIndex) {
        // open the item in question
        openQv(items[ itemIndex ]);

        var nextItemIndex = itemIndex + 1;

        // ensure it exists
        if (!items[ nextItemIndex ]) {
            return;
        }

        setTimeout(function() {
            handleItem(nextItemIndex);
        }, delayBetweenItems);
    }

    handleItem(0);
}

open(sliderArray, 200);

这将在每个项目之间等待200毫秒,以便您获得渐进效果

相关问题