javascript - SetTimeout 在 Angular js 中失败?

标签 javascript angularjs settimeout

我想增加每秒的计数。所以我使用 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);
        }
    }
}

演示:http://plnkr.co/edit/CAfwGRa5M1BmBC3s8cKa?p=preview

关于javascript - SetTimeout 在 Angular js 中失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25401942/

相关文章:

javascript - 在没有 ES6 模块的情况下使用 jest

javascript - 在 Laravel 中使用数组将数据从 View ( Blade )传递到 Controller

javascript - 未定义值 : angularjs $scope and web3. eth.getBalance

node.js - 使用 AngularJS 在 node.js 中查看模板和路由

javascript - 延迟 javascript 执行直到 DOM 更改完成

javascript - 有没有办法在 Javascript 中进行下一次迭代之前等待计算

javascript - 对每个元素应用自定义 Angular 过滤器

AngularJs 将当前浏览器选项卡中的更改反射(reflect)到其他选项卡

javascript - jquery 这不适用于 settimeout,bug?

javascript - 再次调用函数时如何清除这些 setTimeouts