Implement Countdown Timer in decreasing order in AngularJS

Last Reply 3 months ago By dharmendr

Posted 3 months ago

How to set the timer when the page load in AngularJS?

I want a timer control in reverse order. Timer is used for exam application.

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Hi SUJAYS,

There is $interval and $timeout service in AngularJS module. You can use that.

Or you can use JavaScript setInterval function.

Check this example. Now please take its reference and correct your code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AngularJS Timer</title>
</head>
<body>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.controller('MyController', function ($scope, $interval, $timeout) {
            // Using timeout.
            $scope.Counter = 10;
            $scope.Timeout = function () {
                $scope.Counter--;
                timeout = $timeout($scope.Timeout, 1000);
                if ($scope.Counter == 0) {
                    $timeout.cancel(timeout);
                }
            }
            var timeout = $timeout($scope.Timeout, 1000);

            // Using interval.
            $scope.CountDown = 10;
            $interval(function () {
                if ($scope.CountDown > 0) {
                    $scope.CountDown--;
                }
            }, 1000, 0);

            // Using setInterval.
            $scope.Timer = 10;
            var timer = setInterval(function () {
                if ($scope.Timer > 0) {
                    $scope.Timer--;
                    $scope.$apply();
                }
            }, 1000);
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <b>{{Counter}}</b><hr />
        <b>{{CountDown}}</b><hr />
        <b>{{Timer}}</b>
    </div>
</body>
</html>

Demo