简体   繁体   English

如何在JavaScript循环中添加其他延迟?

[英]How do I add a different delay in a JavaScript loop?

i'd like to call a function with a specific timer. 我想用一个特定的计时器来调用一个函数。 I already know about setTimeout() function, but i got a problem, here it is : 我已经知道setTimeout()函数,但是我遇到了一个问题,这里是:

// mysounds is an array of audio div

mysounds .forEach(function(value, i) {
    myLoop($("#"+value+"_s")[0].duration*1000);
    // I call my function with the duration of the sample from the audio div in parameter
});

function myLoop (timer){           
    setTimeout(function (){    
        alert('hello');
    }, timer);
}

So, as you can see the forEach loop will be call asynchronously --> all the sounds in the array will be play at the same time and i want them to be play one after the other.. 因此,正如您所看到的,forEach循环将被异步调用->数组中的所有声音将同时播放,我希望它们一个接一个地播放。

You can use promises for this, promises represent calculating an eventual value rather than an immediate one. 您可以为此使用诺言,诺言表示计算最终值,而不是立即值。 First, let's convert setTimeout to a promise: 首先,让我们将setTimeout转换为setTimeout

function delay(ms){
    var dfd = $.Deferred();

    setTimeout(function(){
        dfd.resolve();
    }, ms);

    return dfd.promise();
}

now, let's chain our objects. 现在,让我们链接对象。 I assume you have references to them in an array: 我假设您在数组中引用了它们:

var elements = [el1,el2,el3]; // elements is an array of elements, you can convert
                              // that representation you have now with a loop.

var result = delay(0); // initial value
elements.forEach(function(el){
      result = result.then(function(){ // when our current delay expires
           alert("Hello"); // element available here as `el`
           return delay(1000); // next, wait 1000 ms
      });
});
result.then(function(){
     // in here, everything is resolved.
});

Fiddle 小提琴

     var index = 0,
         timer = 1000;

     setinterval(function () {
                 alert (index)
                 index++;

               }, timer);

This might help you in calling your function every 1 second, but if you want to change your timing, need to clear setinterval and pass in a new timer, 这可能会帮助您每1秒调用一次函数,但是如果您想更改计时,则需要清除setinterval并传入新的计时器,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM