延迟 JavaScript 函数的执行
我有一个 JQuery 的 .each
循环,每次迭代都会调用一个带有参数的函数,有没有办法延迟这个函数调用?我已尝试如下所示的 setTimeout
,但这不起作用,因为该函数会立即执行。
$.each(myArray, function (j, dataitem)
{
setTimeout(function () { showDetails(dataitem) }, 300);
});
function showDetails(dataitem)
{
...
}
数组大小大约为 20,我想做的是在一定的时间范围内而不是立即分配函数调用,知道如何实现这一点吗?我准备重写和重构如何调用函数来完成此任务,任何帮助将不胜感激。
I have a JQuery's .each
loop that calls a function with a parameter per iteration, is there a way to delay this function call? I have tried setTimeout
as in the following but this does not work as the function gets executed immediately.
$.each(myArray, function (j, dataitem)
{
setTimeout(function () { showDetails(dataitem) }, 300);
});
function showDetails(dataitem)
{
...
}
Array size is roughly 20, What I'm trying to do is to distribute function calls over a certain time frame instead of immediately, any idea how to achieve this? I'm prepared to rewrite and restructure how functions get called to get this done, any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用数组的索引来动态计算间隔:
You could use the index of the array to calculate the interval dynamically:
您可以在 300 毫秒后全部执行它们。相反,尝试这样的事情:
编辑:与其一次创建 20 个计时器,我认为最好一个接一个地执行。函数应该是:
第一次调用可以是:
这假设 myArray 是普通的全局数组,并且将处理一个项目,然后才延迟调用下一个项目。
You execute them all after 300 milliseconds. Instead, try something like this:
Edit: instead of creating 20 timers at once I think it's better to do it one by one. Function should be:
And first call can be:
This assume
myArray
is plain global array, and will handle one item and only then call the next item with delay.看看
jQuery.queue([queueName],callback(next))
。这允许您对要调用的函数进行排队,这也是 jQuery 动画效果在内部使用的。
听起来您想实现一个队列,尽管尚不完全清楚您这样做的意图。
编辑:重新阅读您的问题,我认为其他答案更符合您的要求,但是我想我会向您展示一个如何使用自定义队列实现延迟函数执行的示例。
如何使用队列的示例。
Take a look at
jQuery.queue([ queueName ], callback( next ))
. This allows you to queue functions up to be called and is what jQuery's animation effects use internally.It sounds like you would like to implement a queue, although it is not entirely clear you intentions for doing so.
EDIT: re-reading your question, I think other answers better match what you are after, however I thought that I would show you an example of how to achieve delayed function execution with a custom queue.
An example of how you could use a queue.
只是不要使用
$.each
,而是类似:Just don't use
$.each
, but something like: