AngularJS覆盖(取消)超时(如果已存在)

时间:2019-07-02 05:42:18

标签: javascript angularjs angularjs-service

我有服务

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

可以删除指定的范围变量, 我使用上述服务在消息创建5秒后从变量中删除消息,每当在同一个作用域变量中创建新消息时,它都需要等待5秒钟,然后才应该删除它,但是问题是什么时候以前有超时在起作用在同一作用域变量上,应使用新的超时值覆盖它,因此消息必须显示5sec,任何人都可以帮助我谢谢您。

2 个答案:

答案 0 :(得分:0)

我在这里完全是盲人,请根据假设写出此答案,并尝试理解该摘要以供使用!

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);
        }
    }
}; 

答案 1 :(得分:0)

保存$timeout返回的承诺,并使用它来取消先前的$ 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);
    }
});

该服务根据范围的$id和变量名称来构造ID。它存储$timeout返回的承诺,并用它来取消先前的$timeout

有关更多信息,请参见