如何在JavaScript循环中添加不同的延迟?
我想用特定的计时器调用函数。 我已经知道setTimeout()函数,但我遇到了一个问题,这里是:如何在JavaScript循环中添加不同的延迟?,javascript,jquery,promise,Javascript,Jquery,Promise,我想用特定的计时器调用函数。 我已经知道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 di
// 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);
}
因此,正如您所看到的,forEach循环将被异步调用-->数组中的所有声音将同时播放,我希望它们一个接一个地播放。您可以使用承诺来实现这一点,承诺表示计算最终值,而不是立即值。首先,让我们将
setTimeout
转换为承诺:
function delay(ms){
var dfd = $.Deferred();
setTimeout(function(){
dfd.resolve();
}, ms);
return dfd.promise();
}
现在,让我们将对象链接起来。我假设在数组中有对它们的引用:
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.
});
这可能有助于你每1秒调用一次函数,但是如果你想改变你的时间,需要清除StTealStand并通过一个新的定时器,
有<代码> $(“γ”+值)通常是一个强烈的指示,你应该考虑学习数组。此外,将任意值保存为DOM元素的属性可能有效,也可能无效,我绝对不会指望它。请考虑更多的关于清洁设计的关注点的分离和对你的演示逻辑和你的数据和逻辑模型的支持,我想它会对你有很大帮助。在这类事情上,承诺实际上是非常令人惊讶的,并且通常非常有用。你可能想读更多关于它们的书,因为它们让你的生活变得无比轻松。正如我之前所说的,我真的相信“#”+id
会导致最近发现的严重bug,我建议改为使用数组:)编码愉快,祝你好运。
var index = 0,
timer = 1000;
setinterval(function () {
alert (index)
index++;
}, timer);