我想增加每秒的计数。所以我使用 do while 循环,但它使浏览器崩溃。
代码:
do{
$scope.timer = 0;
console.log($scope.timer);
setTimeout(function(){
$scope.$apply(function(){$scope.timer = $scope.timer+1;
return $scope.timer; });
}, 1000);
}while($scope.timer < $scope.level._seconds_per_question);
有人可以建议我哪里出错了吗?
最佳答案
首先,有一个原生的 Angular 服务 - $timeout
它允许您执行超时而无需调用 $scope.$apply 。
所以,你可以这样做:
function MyController($scope, $timeout) {
$scope.timer = 0;
$scope.level = {
// I assume this object is declared in a parent $scope in your code.
// I define it here just so the sample will work.
_seconds_per_question: 10
};
$timeout(increment, 1000);
function increment() {
if ($scope.timer < $scope.level._seconds_per_question) {
console.log($scope.timer);
$scope.timer ++;
$timeout(increment, 1000);
}
}
}
关于javascript - SetTimeout 在 Angular js 中失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25401942/