安全和正确的方式来重新加载angularjs数据($超时) [英] Safe and correct way to reload data on angularjs ($timeout)

查看:198
本文介绍了安全和正确的方式来重新加载angularjs数据($超时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个code到安全工作与 $超时

I use this code to safe work with $timeout :

        $scope.intervalFunction = function () {
            setTimeout(function () {
                //DO
                console.log('refresh');
                if ($scope.currentNode) {
                    $scope.intervalFunction();
                }
            }, 5000)
        };

        function setTimeout(fn, delay) {
            var promise = $timeout(fn, delay);
            var deregister = $scope.$on('$destroy', function () {
                $timeout.cancel(promise);
            });
            promise.then(deregister);
        }

        $scope.intervalFunction();

这是正确的?

推荐答案

有一些优化这里,如果它是总是需要在超时被执行相同的功能:

There are a few optimizations here, if it is always the same function that needs to be executed in the timeout:

var refreshTimeout;

$scope.intervalFunction = function () {
    // Assign to refreshTimeout, so it can be cancelled on the destroy of the scope
    refreshTimeout = $timeout(function() {
        console.log('refresh');
        if ($scope.currentNode) {
            $scope.intervalFunction();
        }
    }, 5000)
};

$scope.intervalFunction();

// Only one timeout to destroy
// Though I don't think this is even necessary, because probably
// the timeout gets cancelled anyway on the destruction of the scope
$scope.$on('$destroy', function () {
    if (refreshTimeout)        
        refreshTimeout.cancel();
});

修改

据<一个href=\"http://www.bennadel.com/blog/2548-don-t-forget-to-cancel-timeout-timers-in-your-destroy-events-in-angularjs.htm\"相对=nofollow>这个文章中,你需要摧毁超时自己:)

According to this article, you do need to destroy the timeout yourself :)

这篇关于安全和正确的方式来重新加载angularjs数据($超时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆