延迟JavaScript的函数执行

我有一个JQuery的.each循环,每次迭代调用一个参数的函数,有没有办法延迟这个函数调用? 我已尝试过setTimeout,如下所示,但这不起作用,因为函数立即执行。

$.each(myArray, function (j, dataitem) { setTimeout(function () { showDetails(dataitem) }, 300); }); function showDetails(dataitem) { ... } 

数组大小大约是20,我要做的是在一定的时间范围内分配函数调用而不是立即,任何想法如何实现这一点? 我准备重写并重新调整函数的调用方式来完成这项工作,任何帮助都将受到赞赏。

您可以使用数组的索引动态计算间隔:

 $.each(myArray, function (j, dataitem) { window.setTimeout(function () { showDetails(dataitem) }, (j + 1) * 300); }); 

你在300毫秒后执行它们。 相反,尝试这样的事情:

 window.setTimeout(function () { showDetails(dataitem) }, (j + 1) * 300); 

编辑:不要一次创建20个计时器,我认为最好一个一个地完成。 function应该是:

 function showDetails(index) { if (index >= myArray.length) return false; var dataItem = myArray[index]; //code here...... //code here...... //code here...... windows.setTimeout(function() { showDetails(index + 1); }, 300); } 

第一个电话可以是:

 $(document).ready(function() { { showDetails(0); }); 

假设myArray是普通的全局数组,它将处理一个项目,然后才会延迟调用下一个项目。

看一下jQuery.queue([ queueName ], callback( next )) 。 这允许您对要调用的函数进行排队,这是jQuery的动画效果在内部使用的。

听起来你想要实现一个队列,尽管你并不完全清楚这样做的意图。

编辑:重新阅读你的问题,我认为其他答案更符合你的想法,但我想我会告诉你一个如何用自定义队列实现延迟函数执行的例子。

一个如何使用队列示例

 var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], output = $('#output'); // set the queue up $.each(myArray, function (j, dataitem) { output.queue('queue', function(next) { var that = this; showDetails(dataitem); window.setTimeout(next,300); }); }); // start the queue running. output.dequeue('queue'); function showDetails(dataitem) { output.append('
' + dataitem + '
'); }

只是不要使用$.each ,但是类似于:

 var data = [1, 2, 3, 4, 5]; function showDetails(values, delay) { console.log(values.shift()); //show the value if (values.length) { setTimeout(function() {showDetails(values, delay); }, delay); //schedule next elem } } showDetails(data.slice(0), 300); //dont forget the slice, call-by-reference 
Interesting Posts