有什么方法可以在循环中在javascript中睡觉吗?
例如,有一个循环,我想睡几秒钟。
$.each(para.res, function (index, item) { Sleep(100); });
我知道我可以使用setTimeout或setInterval,但它们都是异步的,循环将继续,只要我这样做,setTimeout中的函数将在几秒钟内运行。
$.each(para.res, function (index, item) { setTimeOut(function(){do something},1000); });
您可以定义一个function。
var i = 0; function recursive() { setTimeout(function(){ var item = para.res[i]; // do something i++; if (i < para.res.length) recursive() }, 100) }
不,没有内置的方法。 您可以使用繁忙的循环,但这会在同一时间冻结浏览器,并且您无法执行太长时间,因为浏览器将停止脚本。
如果您希望随着时间推移分散不同的代码片段,只需为setTimeout
设置不同的时间:
$.each(para.res, function (index, item) { setTimeOut(function(){do something},1000 * index); });
这将在一秒钟后启动第一个项目的代码,在两秒钟后启动第二个项目的代码,依此类推。
或者使用setInterval
:
var index = 0, timer = setInterval(function(){ if (index < para.res.length) { var item = para.res[index]; // do something index++; } else { clearInterval(timer); } }, 1000);