本文介绍了延迟JavaScript的函数执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)
{
...
}

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

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.

推荐答案

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

You could use the index of the array to calculate the interval dynamically:

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

这篇关于延迟JavaScript的函数执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:16
查看更多