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.
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.
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.
<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
Demo
Downloads