Angularjs override (cancel) timeout if already exist

127 Views Asked by At

I have a service

devApp.factory('flashFactory',['$timeout',function($timeout){
    var flashFactory = {};
    flashFactory.request = function($scope,variable){
        $timeout(function(){
            delete $scope[variable];
        },5000);
    }
    return flashFactory;
}]);

which can delete the specified scope variable, I use above service to delete the message from the variable after 5sec of message creation, whenever a new message is created in the same scope variable it needs to wait 5sec after that it should delete, but problem is when there is any previous timeout is working on the same scope variable it should be overridden with new timeout, so the message must display 5sec , anyone help me thank you.

2

There are 2 best solutions below

0
Ravikumar Rajendran On

I am completely blind here, Wrote this answer based on assumption and Try to understand this snippet befor use!

devApp.factory('flashFactory', ['$timeout', function($timeout) {
    var flashFactory = {};
    flashFactory.timeoutArr = [];
    flashFactory.request = function($scope, variable) {
        flashFactory.timeoutArr.ifFindThenDelete(variable, $timeout);
        var timeOutObj = {};
        timeOutObj.myvar = variable;
        timeOutObj.fn = $timeout(function() {
            delete $scope[variable];
        }, 5000);
        flashFactory.timeoutArr.push(timeOutObj);

    }
    return flashFactory;
}]);


Array.prototype.ifFindThenDelete = function(variable, $timeout) {
    var i = this.length
    while (i--) {
        if (this[i].myvar == variable) {
            $timeout.cancel(this[i].fn)
            this.splice(i, 1);
        }
    }
}; 
0
georgeawg On

Save the promise returned by the $timeout and use it to cancel the previous $timeout:

devApp.service('flashFactory',function($timeout){
    var promiseCache = {};
    this.request = function request($scope,variable){
        var id = $scope.$id + variable;
        promiseCache[id] && $timeout.cancel(promiseCache[id]);
        promiseCache[id] = $timeout(function(){
            delete $scope[variable];
        },5000);
    }
});

The service fabricates an ID based on the $id of the scope and the name of the variable. It stores the promise returned by the $timeout and uses it to cancel the previous $timeout.

For more information, see