是否有任何方法在循环中的JavaScript中睡觉? [英] Is there any method to sleep in javascript in a loop?
本文介绍了是否有任何方法在循环中的JavaScript中睡觉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,有一个循环,我想睡几秒钟。
For example, there is for loop that I want to sleep for some seconds.
$.each(para.res, function (index, item) {
Sleep(100);
});
我知道我可以使用setTimeout或setInterval但它们都是异步的,循环将继续,只是如果我这样做,setTimeout中的函数将在几秒钟内运行。
I know I can use setTimeout or setInterval but both of them are asychronous, the loop will continue, just the function in the setTimeout will run in a few seconds if I do it this way.
$.each(para.res, function (index, item) {
setTimeOut(function(){do something},1000);
});
推荐答案
您可以定义一个函数。
var i = 0;
function recursive() {
setTimeout(function(){
var item = para.res[i];
// do something
i++;
if (i < para.res.length) recursive()
}, 100)
}
这篇关于是否有任何方法在循环中的JavaScript中睡觉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文