javascript - AngularJs 停止特定 Controller 的 $interval

标签 javascript angularjs events setinterval

我在第一个 Controller 中使用 $interval 来运行某些功能。重定向到第二个 Controller 后,$interval 注册函数(在第一个 Controller 中实现)仍在运行。我想在不使用 destroy 函数的情况下停止 $interval 服务。

最佳答案

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.

您可以使用cancel 方法来清除$interval 对象。您应该在离开 Controller 时取消 interval

为此你需要在 $scope$destroy 事件上添加 eventListener,你可以做一些清理工作(例如取消间隔对象,取消超时对象)。

代码

var myInterval = $interval(function(){
   //your interval code
}, 1000)

//register this listener inside your controller where the interval belongs.
$scope.$on('$destroy', function(){
    $interval.cancel(myInterval)
});

Sample Plunkr

关于javascript - AngularJs 停止特定 Controller 的 $interval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196098/

相关文章:

javascript - 如何调用一个函数另一个函数作为参数传递为字符串

javascript - 如何触发从顶部窗口到 iframe 的事件?

javascript - 记住在函数中使用的搜索查询

安卓 : Multi touch and TYPE_SYSTEM_OVERLAY

python - 我想限制 Tkinter 回调运行的频率

javascript - 为什么 Mobify 在自托管时无法工作?

javascript - 在 PHP 中使用邮件功能时正确转义 JavaScript 文档代码中的特殊字符

javascript - 代码混淆在javascript中真的有用吗?

javascript - 来自 Python json.dumps 的 JSON 响应

javascript - AngularJS 通过 URL ui-router 简单导航到参数化状态