下面是我的代码最简单的形式,我循环遍历一个数组并在每次迭代中删除一个随机项,直到循环长度为 0。我想在每次迭代中添加 sleep 或延迟,但我不确定在 angular1.x 或普通 js 中实现此目的的最佳方法。
我发现了这个问题What is the JavaScript version of sleep()?但无法获得最高评价的工作答案。
任何人都可以帮忙解决这个问题吗:
while($scope.players.length > 0){
random = Math.floor(Math.random() * $scope.players.length);
$scope.players.splice(random, 1);
}
最佳答案
您可以使用setInterval为此目的
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
Tip: 1000 ms = 1 second.
Tip: To execute a function only once, after a specified number of milliseconds, use the setTimeout() method.
示例
function _do(){
if($scope.players.length > 0){
random = Math.floor(Math.random() * $scope.players.length);
$scope.players.splice(random, 1);
} else clearInterval(_loop);
}
var _loop = setInterval(_do,1000); //Sleep for 1 sec
关于javascript - 超时或在循环内休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44257193/