Pulse7
9/9/2017 - 9:28 AM

Countdown $interval timer

(function () {
    let MainController = function ($scope, $interval) {
        let intervalToken;
        const countdownStartNumber = 5;
        const countdownEndAction = function(){
            console.log("Countdown ended");
        }
        const decrementCountdown = function(){
            $scope.countdown--;
            if ($scope.countdown<1)
                countdownEndAction();
        }
        $scope.resetCountdown = function(){
            $scope.stopCountdown();
            $scope.countdown=countdownStartNumber;
        }
        $scope.startCountdown = function(){
            if (stopped){
                intervalToken=$interval(decrementCountdown,1000,$scope.countdown);
                stopped = false;
            }
        }
        $scope.stopCountdown = function(){
            stopped = true;
            $interval.cancel(intervalToken);
        }
        $scope.countdown = countdownStartNumber;
        let stopped=true;
        $scope.startCountdown();
    }

    var app = angular.module("App", []);
    app.controller("MainController", MainController);
})();
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="App">
    <div ng-controller="MainController">
        <h1>{{countdown}}</h1>
        <button ng-click="stopCountdown()">Stop</button>
        <button ng-click="resetCountdown()">Reset</button>
        <button ng-click="startCountdown()">Start</button>
    </div>
</body>
</html>