This question already has answers here:
What is the JavaScript version of sleep()?

(80个答案)


7年前关闭。




我有一个Java Script函数,需要未定义的时间来完成。在一个循环中,我想等待功能完成,然后等待定义的时间(例如5000毫秒),然后再次调用该功能。如何在Java脚本中完成此操作?

基本上我想要这样:
call function and wait until it is finished
wait another 5000 seconds
call function and wait until it is finished
wait another 5000 seconds
...

该函数本身看起来像这样:
for every group in list

    .ajax(delete group items; get group items; add group items)

我目前遇到的问题是,在循环的中间,该函数以某种方式再次被调用。

最佳答案

创建一个在计时器末尾递归调用自身的函数:

(function my_func() {
    // your code
    setTimeout( my_func, 5000 );
})();

这会立即调用my_func,然后在5秒钟的延迟后在函数末尾递归调用它。

这样,计时器直到代码完成才开始。

您可以将setTimeout()放在if语句中,以使递归依赖于某些条件:
(function my_func() {
    // your code
    if( some_criteria_is_met ) {
        setTimeout( my_func, 5000 );
    }
})();

请注意,这意味着您的代码是同步的。如果您正在运行一些异步代码(例如AJAX请求),则方法会有所不同。

09-25 17:48
查看更多