Stop interval when not visible

I need to stop a interval when the controller is not visible.

Is there a event when the controller-page goes to background?

“Controller is not visible” ?

M.

@ziobudda: I think he means when you leave a view.

@Sebastian345234: Listen to $destroy event in your controller and cancel your interval in there.

Basically add this to your controller and that’s all that should be needed:

$scope.$on("$destroy", function (event) {
    if ( yourIntervalTimer ) {
        $interval.cancel( yourIntervalTimer );
    }
});

Of course, replace yourIntervalTimer with variable that you assigned your interval to.

2 Likes

@lrolecek: or the user has scrolled and the controller’s html tag (div, span, p, etc etc) is no more visible. It’s like a method to stop a video if it is no visible.

However, thanks for the $destroy. I don’t knowed it.

M.

Perfect - it works! thx!

Is there a way to catch when the whole application goes to background ?
Like when user switches between app and leaves it running in background ?

Yes there is, @koko.

You start listening to app pause/resume event like this:

myAppPause = $ionicPlatform.on('pause', myAppPauseFunction);
myAppResume = $ionicPlatform.on('resume', myAppResumeFunction);

You do whatever you need to do in myAppPauseFunction / myAppResumeFunction - for example you can stop your $interval and then resume it when app is brought from background again.

When you don’t need those events anymore, you dispose of them like this:

myAppPause();
myAppResume();

Here’s the documentation for pure Cordova solution that can give you more details:
http://cordova.apache.org/docs/en/4.0.0/cordova_events_events.md.html

$ionicPlatform.on() is basically just a wrapper around Cordova events but I prefer to use it because it feels “native” when developing Ionic apps.

Nice! Will try it, thanks!