NVO
NVO

Reputation: 2713

Countdown in Angular, with restart

I have created a simple dashboard with some data as a tryout in Angular. With PHP I get some weather data, news via Google News and 10 tweets about a keyword.

With the $interval I refresh the dashboard every 10 seconds, but I want a countdown from 10 to 0, which starts over and over when the interval is triggered.

Can somebody help me to achieve this?

Current code as submitbutton and $interval trigger:

$scope.formSubmit = function(){ 
    $scope.getResults();
    if($scope.interval){            
        intervalController();
    }
}

function intervalController(){
    $interval($scope.getResults, 10000);
}

$scope.getResults = function(){
    if($scope.city){
        $http({
            method: 'POST',
            url: 'server.php',
            data: {city : $scope.city}
        }).then(function successCallback(response){
            console.log(response.data);
                //some data processing here
        }, function errorCallback(response){

        })
    }
}

Upvotes: 0

Views: 82

Answers (1)

Julien TASSIN
Julien TASSIN

Reputation: 5212

$scope.initialCountDownValue = 10;
$scope.countDownValue = $scope.initialCountDownValue;
var intervalCanceller = null;

$scope.formSubmit = function(){ 
    $scope.getResults();
    if($scope.interval){            
        intervalController();
    }
}


function decrementCountdown() {
  $scope.countDownValue -= 1;
  if ( $scope.countDownValue === 0) {
    $scope.getResults();
    $scope.countDownValue = $scope.initialCountDownValue;
  }
}

function intervalController(){
    intervalCanceller = $interval(decrementCountdown, 1000);
}

$scope.getResults = function(){
    if($scope.city){
        $http({
            method: 'POST',
            url: 'server.php',
            data: {city : $scope.city}
        }).then(function successCallback(response){
            console.log(response.data);
                //some data processing here
        }, function errorCallback(response){

        })
    }
}

in $scope.countDownValue you have your countdown value to display to the user.

One additional point.

Do not to forget to unsubscribe your $interval on the scope destruction. Or you will have an interval living for ever for nothing. Here is the way to destroy your interval properly :

$scope.$on('$destroy', function() {
  if (intervalCanceller) {
    $interval.cancel(intervalCanceller);
  }
});

Upvotes: 2

Related Questions