Reputation: 1303
I want increment the count for every second. so i am using do while loop but it is crashing the browser.
code:
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);
Could any suggest where i am going wrong?
Upvotes: 0
Views: 126
Reputation: 387
Please find below the code
function Ctrl($scope, $timeout)
{
$scope.timeInMs = 0;
var countUp = function() {
$scope.timeInMs+= 1;
$timeout(countUp, 1000);
}
$timeout(countUp, 1000);
}
Upvotes: 0
Reputation: 4822
First of all, there is a native Angular service - $timeout
which allows you to do timeouts without having to call $scope.$apply
.
So, you could do something like this:
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);
}
}
}
Demo: http://plnkr.co/edit/CAfwGRa5M1BmBC3s8cKa?p=preview
Upvotes: 4