0

I am trying to implement a simple timer in angularJS. But timeout function is not working though it is suggested by everyone.

<!doctype html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-sanitize.min.js"></script>

</head>
<body>

<div ng-app="ss" ng-controller="mainCtrl">
{{timeInMs}}
</div>

<script>
var myApp = angular.module("ss", ['ngSanitize']);
myApp.controller('mainCtrl', function ($sce, $scope) {

    $scope.timeInMs = 10;

        var countUp = function() {
            $scope.timeInMs+= 500;
            $timeout(countUp, 500);
        }

       $timeout(countUp, 500);


});

</script>

</body>
</html>

When I comment out the " $timeout(countUp, 500);" line, the code works without error but timer doesn't work. Do i need to include any more javascript file?

Thanks in advance.

1
  • 1
    You have to inject $timeout into the controller. Commented Sep 18, 2014 at 7:58

1 Answer 1

2

You have to inject the $timeout service to the controller

var myApp = angular.module("ss", []);
myApp.controller('mainCtrl', function ($sce, $scope, $timeout) {

    $scope.timeInMs = 10;

    var countUp = function () {
        $scope.timeInMs += 500;
        $timeout(countUp, 500);
    }
    $timeout(countUp, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ss" ng-controller="mainCtrl">
    {{timeInMs}}
</div>

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

Comments

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.