0

My angular timer function code in App.js look like :-

$scope.counter = 1000;
$scope.countdown = function () {

    stopped = $timeout(function () {
        $scope.counter--;
        $scope.countdown();
    }, 1000);
    if ($scope.counter == 0) {
        $timeout.cancel(stopped);
    }
};

My counter directive look like :-

data.filter('formatTimer', function () {
return function (input) {
    function z(n) { return (n < 10 ? '0' : '') + n; }
    var seconds = input % 60;
    var minutes = Math.floor(input / 60);
    var hours = Math.floor(minutes / 60);
    return (z(hours) + ':' + z(minutes) + ':' + z(seconds));
  };
});

And in my html template code look like :-

 <div class="col-xs-3 col-md-4 push" align="center" ng-init="countdown()">
                            <div class="alt_heade_text">
                                {{counter|formatTimer}}
                            </div>
                        </div>

Timer working fine for me but it decrease time(in seconds) 5 instead of 1, whats going wrong ???

2
  • In my opinion, it's a bit strange use $timeout for timer. It's better to use $interval. Take a look: siddii.github.io/angular-timer Commented Aug 12, 2015 at 4:17
  • Thanks for your suggestion, Can you give one example with it ? Commented Aug 12, 2015 at 5:05

2 Answers 2

1

As Roman suggested, you should probably use $interval instead of $timeout.

Example:

$scope.counter = 1000;
$scope.countdown = function () {

    var timer = $interval(function () {
        $scope.counter--;
    }, 1000, 1000);
};

Here the first and second arguments are like in $timeout - the first one is the function to run every interval, and the second one is the length of the interval. The third one specifies the number of times the interval will be repeated, so setting it to 1000 makes it stop automatically as the counter reaches 0.

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

Comments

0

Please, try this:

$scope.counter = 1000;
var promise=$interval(function(){
    $scope.counter--;
},1000);

$scope.$watch('counter', function(newValue, oldValue) {
    if(newValue==0)
        $interval.cancel(promise);
});

Don't forget inject $interval into your controller.

1 Comment

But Fissio's solution it's much better.

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.