如何在用户离开页面时取消angularjs $ timeout

Mic*_*ael 6 timeout web-applications web angularjs

$timeout用来定期更新我的angularjs应用程序中的一个页面上的信息.$timeout当用户离开此页面时,我想取消.有一个简单的方法吗?

Mic*_*ael 12

好的,我在挖掘后找到了解决方案:

$scope.$on('$destroy', function() {
    $timeout.cancel(timeout);
});
Run Code Online (Sandbox Code Playgroud)

或者对于Angular 1.5中的新组件语法:

this.$onDestroy = function() {
    if (timeout) {
        $timeout.cancel(timeout);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.为了澄清,`timeout`变量是由$ $ timeout(...)`调用返回的计时器id.有关相关问题,请参见http://stackoverflow.com/questions/14897608/cancel-a-angularjs-timeout-on-routechange?rq=1. (4认同)