itamar
itamar

Reputation: 3967

Looping function with time delay in AngularJS

So I'm creating a simple countdown function in AngularJS which is mean to count down to the time set in inputs. The problem is that I'm not able to loop the $scope.countdown function. So it only counts down once (and if I put the $timeout($scope.countdown(), 1000); in - it breaks entirely.) I just want it to loop every second until it reaches 0.

Here's my controller:

function countdownController($scope) {

  $scope.hours = 2;
  $scope.minutes = 30;

  $scope.countdown = function(){
    if($scope.minutes == 0 && $scope.hours == 0){
        alert('end!');
        return;
    }
    else{
        if($scope.minutes == 0){
            $scope.minutes = 59;
            $scope.hours--;
        }
        else{
            $scope.minutes--;
        }

    }
    $timeout($scope.countdown(), 1000); //if I remove this - the numbers display - this actually breaks that.
  }

  $scope.countdown();
}

Upvotes: 1

Views: 6340

Answers (2)

Florian F.
Florian F.

Reputation: 4700

What you're looking for is arguments.callee :

$scope.countdown = function(){
    if($scope.minutes == 0 && $scope.hours == 0){
        alert('end!');
        return;
    }
    else{
        if($scope.minutes == 0){
            $scope.minutes = 59;
            $scope.hours--;
        }
        else{
            $scope.minutes--;
        }

    }
    $timeout(arguments.callee, 1000);
}

Or its more advised alternative :

function countdownController($scope, $timeout) {
    $scope.hours = 0;
    $scope.minutes = 45;
    $scope.countdown = function myhandler() {
        console.log('call');
        if ($scope.minutes == 0 && $scope.hours == 0) {
            console.log('end!');
            return;
        } else {
            if ($scope.minutes == 0) {
                $scope.minutes = 59;
                $scope.hours--;
            } else {
                $scope.minutes--;
            }

        }
        $timeout(myhandler, 1000);
    }
}

JsFiddle Example

NB : as mentionned in the comments, don't forget to inject $timeout into your controller.

Upvotes: 3

Michael
Michael

Reputation: 3104

You have to pass a function to the $timeout service. NOT the result of the function. Try this:

$timeout($scope.countdown, 1000); 

Upvotes: 0

Related Questions