×

$timeout service in AngularJS

The discipline of web development is expanding quickly. A technology that is released today will inevitably become obsolete in a few months. The webpages were static in the past and contained little to no CSS or animation. However, the way webpages used to appear and work radically changed with the arrival of vanilla JavaScript. Using AngularJS, single-page applications (SPAs) are produced. AngularJS has almost 30 built-in services. In addition to this, users can develop their own user-defined services according to the project needs.

The $timeout service

The AngularJS "timeout" service function is similar to the JavaScript "window.setTimeout" object. The developer can set a time delay before the function is executed using this service.

This is represented as ‘$timeout.’ Let's see the syntax of the $timeOut function.

Syntax:

$timeout([fxn],[delay_time],[invokeApply],[parameters]);

Basically, there are four parameters used in the timeout function in AngularJS:

  1. First parameter is fxn which means we will pass the function name which we want to execute after a certain time of period.
  2. The second parameter is delay_time which contains an integer value. This is the time which is given as delay to the function so that the function will get executed after this delay_time. Unit of delay_time is in milliseconds.
  3. The third parameter is invokeApply which is a Boolean variable which will have either a true or false value. By default, the value of this parameter is true. This should be noted that this parameter is an optional parameter as it is not necessary to mention it until we require it. If this parameter is set to false, that means we are ignoring model dirty checking, and if it is set to true, then the function is executed in the $apply block. $apply block is the place or block where all the functions which are not defined in AngularJS are executed.
  4. Fourth parameter is parameters which mean if the execution of the function requires any arguments or parameters then we can pass over here. The return value of $timeout is a promise which will return success after executing the function after a time delay.

Functions that we can use with $timeout

There are a few functions we can use with $timeout:

Cancel function

The cancel function is generally used to stop the execution of any function which is passed into the $timeout service. It returns the promise as rejection because we have cancelled the execution of the function.

Syntax:

$timeout.cancel(promise)

Flush function

Suppose we have more than one function which is going to be executed with some delay using the $timeout service. If we want them to cancel in the sequential way as they were supposed to be executed, then we will use the flush function.

Syntax: 

$timeout.flush()

Let's see some examples implementing the $timeout function:

Example 1:

<!DOCTYPE html>
<html>
<head>
<title>
AngularJs $timeout Service with Example
</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('timeoutApp', []);
app.controller('timeoutCtrl', function ($scope, $timeout) {
$scope.message="Welcome to javatpoint."
$timeout(function () {
$scope.message = "I got internship";
}, 5000);
});
</script>
</head>
<body>
<h1>This is the example for timeout service</h1>
<div ng-app="timeoutApp" ng-controller="timeoutCtrl">
<h1>you will see message changing after 5 seconds delay</h1>
<b>{{message}}</b>
</div>
</body>
</html>

In the above program, we will see the message “I got the internship” after 5 seconds because we have passed this into $timeout function and the time is 5000 milliseconds.

Example2:

<!DOCTYPE html>
<html>
<head>
	<title>JavatPoint</title>
	<script src=
"http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
	<script type="text/javascript">
		(function() {
			var app = angular.module('app', []);
			app.controller(
			'myController', function($scope, $timeout) {				
				$timeout(function() {
					$scope.alertMessage = "Time Up!";
				}, 20000);				
				$scope.currentTime = 0;			
				var clock = function() {
					if ($scope.currentTime< 20000) {
						$scope.currentTime += 1000;
						$timeout(clock, 1000);
					}
				}				
				$timeout(clock, 1000);
			});
		})();
	</script>
</head>
<body>
	<div ng-app="app">
		<div ng-controller="myController">
			<h2>this will run for next 20 seconds</h2>
			<div>Time Now: {{currentTime/1000}} seconds</div>
			<h3>{{alertMessage}}</h3>
		</div>
	</div>
</body>
</html>

Let's try to understand the above example. We have a variable currentTime which is initialized to zero.

We have a function named clock.

Initially, with the help of the $timeout service, for the first time, we will call the clock function with a delay of 1000 milliseconds or 1 second. Whenever we call the clock function, it will set the currentTime to currentTime + 1000. And then it will call $timeout again with 1000 seconds delay.

So, this is the recursive call to the $timeout at each second till the 20 seconds. After 20 seconds, it will stop.


Related Topics

Angular 8 Libraries

Angular libraries are built a solution of general problems like presenting a unified user interface, presenting data, and allowing the data entry. Developers can create standard solutions for particular domains...

3 minutes read.

Angular 8 Unit Testing

What is unit testing? Unit testing is a type of software testing where individual components of the software are tested. It is done during the development of any application. A unit may be...

6 minutes read.

Angular 8 File Structure

File Structure in Angular 8: A file structure contains the files for one or more projects. A project is the set of files that comprise an application on a shareable...

3 minutes read.

Data Binding in Angular 8

What is Binding? Binding is the process which generates the connection between the application UI and the data which comes from the business logic. In Angular, it is called the automatic synchronization of...

3 minutes read.

Angular CLI Commands

All CLI commands of Angular Angular CLI is a command-line interface which is used to initialize, develop, and maintain Angular applications. We can use these Command on command prompt or consequentially by an associated...

8 minutes read.

Creating form in Angular 8

The angular reactive form is used to handle the user's input. We can use Angular form in the application to authorize the user to log in, to update profile, to enter information,...

2 minutes read.

String Interpolation in Angular 8

String Interpolation in Angular 8 String interpolation is a one-way data-binding technique which is used to output the data from a typescript code to HTML template. It uses the template expression. It uses the...

2 minutes read.

ngSwitch Directive in Angular 8

Angular 8 ng-Switch Directive The ng-Switch Directive hides and shows the HTML elements depending on an expression. Child elements with the ng-switch-when directive will be displayed if it gets a match; otherwise, the component and...

2 minutes read.

$timeout service in AngularJS

The discipline of web development is expanding quickly. A technology that is released today will inevitably become obsolete in a few months. The webpages were static in the past and...

4 minutes read.

Angular 8 Forms

Angular forms are used to handle the user's input. We use Angular form in our application to authorize users to log in, to update profile, to enter information, and to perform many other...

3 minutes read.

Property binding in Angular 8

Property binding is the primary way to binding data in Angular.  To bind data to a property of any element, we use square braces[ ]. It is also a one-way data-binding...

2 minutes read.

Angular 8 Module

Angular 8 Module It is a collection of services, directives, controllers, filters, and configuration information. angular.module is used to configure the $injector. The module is a container of the different parts of an application....

6 minutes read.

Angular 8 Components

Angular is used for building mobile and desktop web applications. The component is the basic building block of Angular. It has a selector, template, style, and other properties, and it...

4 minutes read.

Angular 8 Pipes

Angular 8 Pipes Pipes are a useful feature in Angular. These are the simple way to transform values in an Angular template. It takes the integers, strings, array, and dates as input separated with...

3 minutes read.

History and Versions of Angular 8

Introduction to Angular JS Misko created Angular JS and the first version of Angular also name as "Angular 1". He built a framework to handle the downfalls of HTML. The first...

3 minutes read.

How to create a Todo List App in Angular 7

What is a Todo List App? Todo List app is an app where users can add various tasks that they want to perform and have an idea of every task. If...

4 minutes read.

Angular 8 Architecture

Architecture of Angular 8 Angular 8 is a platform and framework which is used to create clients applications in HTML and Typescript. Angular 8 is written in Typescript. Typescript is a...

5 minutes read.

Angular 8 changes and new features

The angular version number indicates the level of changes introduced by the release. The use of semantic versioning helps us understand the potential impact of updating to a new version. Angular is the...

5 minutes read.

Angular 8 NgStyle Directive

Angular 8 NgStyle Directive The ngStyle attribute is used to change and style the multiple properties of Angular. We can change the value, color, and size, etc. of the component. It is a built-in...

1 minute read.

Angular 8 *ngFor Directive

Angular 8ngFor Directive The *ngFor directive is used to repeat to repeat a portion of HTML template once per each item from an iterable list (collection). The ngFor is an Angular...

2 minutes read.