0

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?

3
  • Can u please give the full controller code... Commented Aug 20, 2014 at 10:16
  • @parthicool05 , I am using this code in inside of interval function. There is nothing more than this code. I am failing here it self. Commented Aug 20, 2014 at 10:20
  • Friend where did u write this code it is inside of the controller or not.. Commented Aug 20, 2014 at 10:23

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

Please find below the code

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/

4 Comments

@CaspNZ: I have modified the code as well as i have created the jsfiddle for this
@Archana, Could you tell where is that jsfiddle link?
@Anusha: Cannot you see my above shared jsfiddle link along with my answer?[sample]jsfiddle.net/archanagw2010/fq4vg/776 Can you please let me know either you can access that or not?
@Archana, Sorry page is not refreshed before

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.