This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

$interval

1:36 Angular 1.x lesson by

$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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

$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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?