61

I have several $timeout expressions in Modal controller

App.controller('ModalCtrl', function ($scope, $timeout) {
    for (var i = 0; i < 10; i++) {
        (function () {
            var timer = $timeout(function () {
                console.log('timer')
            }, 1000);
        })()
    }
})

I need to clear all the timers when invoking the modal:

App.controller('MainCtrl', function ($scope, $modal, $timeout) {
    $scope.showMap = function () {
        var modal = $modal.open({
            templateUrl: 'modalap.html',
            controller: 'modalCtrl',
        })

        modal.result.then(function () { //fires when modal is resolving
        }, function () { //fires when modal is invoking
        });
    } })

How can I do that?

PS Sorry for bad code formatting. I don't know why but I cant format it better. I duplicated code here:

1
  • how can you inject a controller like that? Commented Jan 9, 2014 at 11:31

2 Answers 2

144

The $timeout service returns a Promise object which can be used to cancel the timeout.

// Start a timeout
var promise = $timeout(function() {}, 1000);

// Stop the pending timeout
$timeout.cancel(promise);

To cancel all pending timeouts, you need to maintain a list of promises and cancel the complete list when you open the modal.

2

You may also let them cancel themselves by doing this...

(function(){
  var timer = $timeout(function(){
    console.log(timer.$$timeoutId);
    $timeout.cancel(timer);
  }, 1000);
})();
4
  • 18
    This doesn't make sense to me. Why would you cancel a $timeout that is already called?
    – pixelfreak
    Commented Feb 10, 2016 at 8:49
  • I wonder if Angular keeps listeners on that timeout. It looks like so because if you call lots of timeouts, memory keeps growing and eventually lead to a memory leek. Commented Apr 13, 2016 at 10:33
  • I guess you cooooould do that.
    – Matt
    Commented Aug 19, 2016 at 21:59
  • 2
    @pixelfreak Because we can and it's free !
    – Marcky
    Commented Jan 23, 2018 at 18:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.