AngularJS. Clear $timeout when invoking angular-ui modal

JavascriptAngularjsTimeoutAngular Ui

Javascript Problem Overview


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:

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

(function(){
  var timer = $timeout(function(){
    console.log(timer.$$timeoutId);
    $timeout.cancel(timer);
  }, 1000);
})();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3162402View Question on Stackoverflow
Solution 1 - JavascriptnullView Answer on Stackoverflow
Solution 2 - JavascriptSoEzPzView Answer on Stackoverflow