user2301515
user2301515

Reputation: 5117

Javascript, AngularJS and setTimeout function

I want to use a javascript setTimeout with AngularJS, that count value increases after every second:

<!DOCTYPE html>
<html>
    <head>
        <title>MyCount</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="js/angular.min.js"></script>
        <script type="text/javascript">

How to write correctly

    function myController($scope) {
        $scope.count = 1;
        $scope.delayInc = function () {
            $timeout(function () {
                $scope.count += 1;
            }, 1000);
        };
    }
</script>

That the count does not stay to 1?

        <h2>My Second Count: {{count}}</h2>
    </body>
</html>

Thank you

Upvotes: 1

Views: 692

Answers (2)

Mike
Mike

Reputation: 1246

Couple of issues with your code. First, you are defining the delayInc() function, but you are never calling it. So, no $timeout is ever scheduled. This needs to either be called in the controller, or you need to have it be initiated from some event (ng-click for example on a button).

Second, from your description, it sounds like you want it to increment every second. Using $timeout would only increment it once -- one second after delayInc() was called.

Take a look at the following approach, showing both $timeout working as well as using $interval to have it ongoing every second:

<body ng-controller="MainCtrl">
  <p>Count (timeout): {{count}}!</p>
  <button ng-click="delayInc()">Start Delay Timer</button>
  <p></p>
  <p>Count2 (interval): {{count2}}!</p>
  <button ng-click="repeatInc()">Start Interval Counter</button>
</body>


app.controller('MainCtrl', function($scope, $timeout, $interval) {
  $scope.count = 1;
  $scope.count2 = 1;
  $scope.delayInc = function() {
    $timeout(function() {
      $scope.count += 1;
    }, 1000);
  };
  $scope.repeatInc = function() {
    $interval(function() {
      $scope.count2 += 1;
    }, 1000);
  }

Here is the Plunker with all of it working: http://plnkr.co/edit/c0EFB7Lbs6ZjJL5NQf86?p=preview

Upvotes: 1

Kostya Shkryob
Kostya Shkryob

Reputation: 2369

$interval is more relevant for this:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    </head>
    <body ng-app="plunker" ng-controller="MainCtrl">
        {{iterator}}
    </body>
    <script>
        var app = angular.module('plunker', []);

        app.controller('MainCtrl', ['$scope', '$interval', function($scope, $interval) {
            $scope.iterator = 1;
            var interval = $interval(function() {
                $scope.iterator++;
                if ($scope.iterator > 10) {
                    $interval.cancel(interval);
                }
            }, 1000);
        }]);
    </script>
</html>

Upvotes: 2

Related Questions