![]() |
VOOZH | about |
Web development is a rapidly growing field. A technology introduced today is bound to get outdated within a few months. Earlier, the websites used to be static, with little to no animation or CSS. However, the introduction of vanilla JavaScript completely revolutionized the way websites used to look and function. But as stated earlier, soon the users got fed up and started looking for something fresh and out of the box. This was when AngularJS entered the market and completely changed the way websites used to function.
Single Page Applications(SPAs) are created using AngularJS. There are around 30 built-in services in AngularJS. Other than these, the users can also create their own user-defined services, as per the project requirements. In this article, we will see the '$timeout' service of AngularJS.
The β$timeoutβ service of AngularJS is functionally similar to the 'window.setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
For instance, Suppose the developer wants to display a warning message on the user's screen, 2 seconds after the user logs in. He can use the $timeout function of AngularJS to create such functionality.
var app = angular.module('timeoutApp', []);
app.controller('timeoutCtrl', function ($scope, $timeout) {
$scope.text="Enter username and password to login"
$timeout(function () {
$scope.text = "Do not share your username and password with anybody";
}, 2000);
});
Example 1: In this example, it is evident that the warning message gets displayed 2000 milliseconds after the user logs in.
Explanation: Here, the $timeout service has been used to create a delay of 4 seconds. This is why the welcome message changes 4 seconds after the page loads.
Output:
Example 2: This example demonstrates a working stopwatch. The stopwatch starts from 0 milliseconds and runs until the timer reaches 15000 milliseconds. After the 15000 milliseconds, mark is reached, and a new message 'Time Up' gets displayed on the screen.
Explanation: Here, a timer function is created. The function starts from 0, and increments by 500 for every 0.5 seconds of time elapse. The timer keeps running until it reaches the 15000 milliseconds mark. A new message 'Time Up' gets displayed on the screen.
Output: