$interval Service Provided by AngularJS

Introduction

In this article I will tell you about the $interval service provided by AngularJS.

An $interval service can be used to trigger any function at a specific milliseconds of time interval, this will trigger the function repeatedly at a given interval of time.

Step 1

First of all you need to add two external Angular.js files to your application, they are:

  • angular.min.js
  • cookies.js

For this you can go to the AngularJS official site or can download my source code and then fetch it or you can click on this link to download it: ANGULARJS.

After downloading the external file you need to add this file to the Head section of your application.

<head runat="server">

    <title></title>

    <script src="angular.min.js"></script>

</head>

Step 2

Now after adding the external JS file the first thing you need to do is to add ng-app in the <HTML> Tag otherwise your application will not run.

<html ng-app xmlns="http://www.w3.org/1999/xhtml">

Now I will work on the JavaScript section of this application.

Write the following code in the head section:

    <script>

        var $interval = function (callback, interval) {

            (function timeout() {

                setTimeout(function () {

                    callback();

                    timeout();

                }, interval);

            })();

        };

 

        $interval(function () {

            document.body.innerHTML += 'I am Generated Through $interval <br>';

        }, 1000);

    </script>

Here I created a function in which the variables callback and interval are defined.

I created a function in which some HTML text is provided, this HTML text will be printed repeatedly after 1000 ms.

Now you don't need to provide anything in the body section. Just run the application and the output will be in front of you.

Output

On running the application you will get an output like this:

interval in AngularJS

After a few ms some more data will be shown.

interval in AngularJS

Now some more:

interval in AngularJS