Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.




    $interval provides an excellent service for timed operations in your AngularJS apps. It has the advantage over setInterval in "normal" Javascript in that it is aware of Angular's view cycles, as well as being mockable for unit tests. Additionally, it returns a promise and provides a lot of flexibility.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    John Lindquist: Angular ships with this $interval service, which allows you to easily create timers based on promises. So if I set up an interval to take a function which runs every tenth of a second and it runs 10 times, then I can grab that all, create a timer and when that's done I can say, "Timer then..."

    I'll create a success function, and just say, "Console log done." You can see that if I refresh this, after a full second it prints out "done." But you probably also want to see the notifications every time that runs, and the way you do that is...

    It also takes and error handler or error callback and a notification callback. So in the notification we'll say, "Updating". Here, if I let it run, you'll see it says "updating" ten times, and then it's done.

    The way that you can actually trigger this error is I have this cancel button, which I'll wire up. So I'll say this cancel that's just bound to an NG click. I can use the interval service to say cancel on that timer promise, and that's what's going to cancel it.

    So if I refresh this, I can hit cancel. And then if I put something in the error, I can say, "Canceled or error." Once I refresh and hit cancel, you can see that it was canceled.