AngularJS Timeout Service ($timeout) with Example

Here we will learn what is timeout function ($timeout) in angularjs, use of timeout function in angularjs and how to $timeout function to set some time delay to execute code in angularjs applications with example.

AngularJS $timeout Service

In angularjs $timeout service is same as window.setTimeout function in javascript. By using $timeout service in angularjs we can set some time delay to execute our functions or methods based on our requirement. 

 

Suppose we have requirement in angularjs application like redirect to another page after 10 seconds. By using $timeout service in angularjs we can achieve this functionality very easily.

Syntax of AngularJS $timeout Service

Following is the syntax of using $timeout service in angularjs applications.

 

var app = angular.module('timeoutApp', []);

app.controller('timeoutCtrl', function ($scope, $timeout) {

$scope.msg="Hi Guest"

$timeout(function () {

$scope.msg = "Welcome to Tutlane.com";

}, 3000);

});

If you observe above syntax we are changing message (msg) text after 3 seconds using $timeout service.

 

Note: In above syntax we passed $timeout as argument to the controller in angularjs. To use service in controller we need to pass $timeout as parameter.

 

We will see simple example of using $timeout service in angularjs application.

AngularJS $timeout Service Example

Following is the example of using $timeout service in angularjs applications.

 

Live Preview

<!DOCTYPE html>

<html>

<head>

<title>

AngularJs $timeout Service with Example

</title>

<script src="http://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.msg="Hi Guest"

$timeout(function () {

$scope.msg = "Welcome to Tutlane.com";

}, 3000);

});

</script>

</head>

<body>

<div ng-app="timeoutApp" ng-controller="timeoutCtrl">

<p>AngularJS $timeout Function Example</p>

<b>{{msg}}</b>

</div>

</body>

</html>

Now we will run and see the output of above angularjs $timeout service application.

Output of AngularJS $timeout Service Example

Following is the result of using $timeout service in angularjs applications.

 

Angularjs $timeout function example output or result