fastread homefastrread library fastread menu

AngularJS : $timeout

Tutorial by:Sumit Chauhan      Date: 2016-08-12 00:25:47

❰ Previous Next ❱

AngularJS has two timer services, $timeout and $interval, which you can use to call functions in your application. The $timeout and $interval services are similar in their functionality to JavaScript's setTimeout() and setInterval() functions (actually belonging to the window object). The functionality of these services is also similar, so I will cover both in this text.

$timeout

The $timeout service can be used to call another JavaScript function after a given time delay. The $timeout service only schedules a single call to the function. For repeated calling of a function, see $interval later in this text.

Injecting $timeout

To use the $timeout service you must first get it injected into a controller function. Here is an example that injects the $timeout service into a controller function:

var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $timeout){

});

Notice the $timeout parameter of the controller function. Into this parameter the $timeout service will be injected by AngularJS, just like any other AngularJS service you would want to use in your controller function.

Scheduling a Function Call

Once the $timeout service is injected into your controller function, you can use it to schedule function calls. Here is an example that used the $timeout service to schedule a function call 3 seconds later:

var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $timeout){

    $timeout(callAtTimeout, 3000);

});

function callAtTimeout() {
    console.log("Timeout occurred");
}

This example schedules a function call to callAtTimeout() after 3 seconds (3000 milliseconds).

If you want to call a function on the $scope object, you can do so like this:

var myapp = angular.module("myapp", []);

myapp.controller("DIController", function($scope, $timeout){

    $scope.callAtTimeout = function() {
        console.log("$scope.callAtTimeout - Timeout occurred");
    }

    $timeout( function(){ $scope.callAtTimeout(); }, 3000);
});

Notice the function passed to the $timeout service. This function calls the callAtTimeout() function on the $scope object.

❰ Previous Next ❱