Understanding $timeout Service In AngularJS

Introduction

The window.setTimeout in JavaScript method executes function or evaluates an expression after a specified number of milliseconds. This function is only executed one time. We need to use setInterval method, if we required executing this function repetitively. It takes three parameters: JavaScript function need to execute, number of milliseconds to wait before executing supplied function and additional parameter (optional). The $timeout service is wrapper around this method. Internally function is wrapped into a try/catch block and if any exception is occurred during the execution, $exceptionHandler service will handle it.

Syntax

  1. $timeout([function], [delay time], [invokeApply], [Pass]);  

Arguments

  • function: function which execution would be delayed.
  • delay time: delay time in milliseconds. The default value of this parameter is 0.
  • invokeApply: AngularJS will invoke the function within $apply block and checking model dirty if it is set to true, else it skips model dirty checking.
  • pass: pass here additional parameters required to execute function.

This service return promise and it will be resolved when delay time has passed.

Example

HTML & Controller

  1. <!DOCTYPEhtml>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>$timeout Service in AngularJS</title>  
  6.     <scriptsrc="angular.js">  
  7.         </script>  
  8. </head>  
  9. <bodyng-app="app">  
  10.     <h4>$timeout Example</h4>  
  11.     <divng-controller="HelloController">  
  12.         <p>After 5 seconds alert box will appear.</p>  
  13.         </div>  
  14.         <script>  
  15.             var app = angular.module("app", []);  
  16.             app.controller("HelloController", function($scope, $timeout)  
  17.             {  
  18.                 $timeout(showMessage, 5000);  
  19.                 functionshowMessage()   
  20.                 {  
  21.                     alert('Hi, Jignesh!');  
  22.                 }  
  23.             });  
  24.         </script>  
  25.         </body>  
  26.   
  27. </html>  

Output:

Output

$timeout.cancel()

This method cancels a task related with the promise. It will be resolved with rejection. This method returns true if task is not executed yet and the task canceled successfully.

Example

HTML and Controller
  1. <!DOCTYPEhtml>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>$timeout Service in AngularJS</title>  
  6.     <scriptsrc="angular.js">  
  7.         </script>  
  8. </head>  
  9. <bodyng-app="app">  
  10.     <h4>$timeout Example</h4>  
  11.     <divng-controller="HelloController">  
  12.         <p>After 10 seconds alert box will appear.</p>  
  13.         <buttonng-click="cancelTimeout()">Cancel Timeout</button>  
  14.             </div>  
  15.             <script>  
  16.                 var app = angular.module("app", []);  
  17.                 app.controller("HelloController", function($scope, $timeout)  
  18.                     {  
  19.                     var timer = $timeout(showMessage, 10000);  
  20.                     functionshowMessage()   
  21.                     {  
  22.                         alert('Hi, Jignesh!');  
  23.                     }  
  24.                     $scope.cancelTimeout = function()   
  25.                     {  
  26.                         $timeout.cancel(timer);  
  27.                     }  
  28.                 });  
  29.             </script>  
  30.             </body>  
  31.   
  32. </html>  
Output

When user click on “Cancel Timeout” button before 10 sec, AngularJS will cancel the task associated with the promise.

The $timeout function return a promise and we can bind it to resolved or reject events. We can cancel the underlying timer by passing promise off to the cancel method of $timeout service. It is very important to cancel timer because in AngularJS, timer is executing even if it is no longer relevant to the state of the application. This will happen silently but it might cause unexpected behavior of the Angular application. It is recommended to call the $timeout.cancel method containing Directive or Controller receives the $destroy event.

Summary

There are many cases where we need some small time delay and in JavaScript, this can be achieved using setTimeout() function. AngularJS provides wrapper service named $timeout. When we call setTimeout function from AngularJS, $scope.apply function need to be called to ensure that all the changes to the scope will be reflected. When we use $timeout service, we need not call $apply function.

Hope this will help you.