繁体   English   中英

SetTimeout在Angular JS中失败了吗?

[英]SetTimeout is failing in angular js?

我想每秒增加计数。 所以我正在使用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

请在下面的代码中找到

function Ctrl($scope, $timeout) 
{
  $scope.timeInMs = 0;  
  var countUp = function() {
    $scope.timeInMs+= 1;
    $timeout(countUp, 1000);
  }    
  $timeout(countUp, 1000);
}

http://jsfiddle.net/archanagw2010/fq4vg/776/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM