javascript - 超时或在循环内休眠

标签 javascript angularjs timeout

下面是我的代码最简单的形式,我循环遍历一个数组并在每次迭代中删除一个随机项,直到循环长度为 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/

相关文章:

javascript - 如何下载文件并停留在MVC中的当前页面

javascript - 如何使用 for 循环为对象属性分配多个值?

javascript - 如何在 AngularJS 中通过一次调用在多个 Controller ($scope)中插入相同的数据?

powershell - 向批处理/powershell 添加超时

javascript - 如何使用jquery或ajax在点击时显示文本?

javascript - 无法使用 FTP 将文件从本地发送到 Node js 项目中的服务器

javascript - 如何防止用户表单忽略 angularjs 中的建议

javascript - 是否可以在自定义指令中使用理解表达式?

angularjs - 为什么 Angular $timeout 会阻止端到端测试?

networking - UNC 上的 PowerShell 操作挂起太久