In this article I will explain with an example, how to use the AngularJS $timeout service to perform a task once after a delay of specific time period.
The AngularJS $timeout service makes use of the JavaScript setTimeout method and works in the exact same way.
 
 

AngularJS $timeout service implementation

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 a Button. The HTML DIV has been assigned ng-bind directive to display messages.
The Button is assigned ng-click directive. When the Start Timer Button is clicked, the StartTimer 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.
 

The $timeout function

The AngularJS $timeout function executes a function once after a specific time delay.
 

Starting the $timeout function

The $timeout function accepts two parameters:
1. The function to be executed.
2. The time delay in Milliseconds.
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 $timeout function is initialized to display Current Time in the HTML DIV after delay of one second.
Note: If you need to know more about getting Current Time in JavaScript, please refer my article JavaScript: Display Current Time.
 
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $timeout) {
            //Initiate the Timer object.
            $scope.Timer = null;
 
            //Timer start function.
            $scope.StartTimer = function () {
 
                //Initialize the Timer to run after delay of 1000 milliseconds i.e. one second.
                $scope.Timer = $timeout(function () {
                    //Display the current time.
                    $scope.Message = newDate();
                }, 1000);
            };
        });
    </script>
   <div ng-app="MyApp" ng-controller="MyController">
        <div>
            Current Time: {{ Message|date:'HH:mm:ss'}}
        </div>
        <br />
        <input type="button" value="Start Timer" ng-click="StartTimer()" />
    </div>
</body>
</html>
 
 

Screenshot

Using $timeout service in AngularJS
 
 

Demo

 
 

Downloads