In this article I will explain how to refresh HTML DIV every N seconds using $interval function in AngularJS.
 
 
AngularJS: Refresh HTML DIV every N seconds using $interval
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
The AngularJS app HTML DIV consists of an HTML DIV and two Buttons. The HTML DIV has been assigned ng-bind directive to display messages.
The two Buttons are assigned ng-click directive. When the Start Timer Button is clicked, the StartTimer function of the Controller gets called and when the Stop Timer Button is clicked, the StopTimer function of the Controller gets called.
Note: If you want to learn more about ng-click directive, please refer my article ng-click directive example.
 
In the following example, when the Start Timer button is clicked, a Message is set as to indicate that the Timer has started and also a $interval function is initialized to display Current Time in the HTML DIV every one second.
When the Stop Timer button is clicked, a Message is set to indicate that the Timer has stopped and the Timer is cancelled.
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $interval, $filter) {
            //Initiate the Timer object.
            $scope.Timer = null;
 
            //Timer start function.
            $scope.StartTimer = function () {
                //Set the Timer start message.
                $scope.Message = "Timer started. ";
 
                //Initialize the Timer to run every 1000 milliseconds i.e. one second.
                $scope.Timer = $interval(function () {
                    //Display the current time.
                    var time = $filter('date')(new Date(), 'HH:mm:ss');
                    $scope.Message = "Timer Ticked. " + time;
                }, 1000);
            };
 
            //Timer stop function.
            $scope.StopTimer = function () {
 
                //Set the Timer stop message.
                $scope.Message = "Timer stopped.";
 
                //Cancel the Timer.
                if (angular.isDefined($scope.Timer)) {
                    $interval.cancel($scope.Timer);
                }
            };
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <div ng-bind = "Message">
        </div>
        <br />
        <input type="button" value="Start Timer" ng-click="StartTimer()" />
        <input type="button" value="Stop Timer" ng-click="StopTimer()" />
    </div>
</body>
</html>
 
 
Screenshot
AngularJS: Refresh HTML DIV every N seconds using $interval
 
 
Demo
 
 
Downloads