javascript - 当我访问另一个状态时停止一个函数

标签 javascript angularjs

我有两个 Controller 。一个页面称为 page1,另一个页面称为 page2。在第 1 页上,我有一个运行动画的代码。我有一个无限调用自身的函数。在这一行中。

.each('end', tick)当动画结束时,它再次启动tick()。

function tick(){
 console.log("hello");
 .
 .
 .
//line 190
 paths.attr('transform', null)
 .transition()
 .duration(duration)
 .ease('linear')
 .attr('transform', 'translate(' + x(now - (limit - 1) * duration) + ')')
 .each('end', tick) //when the transition ends, it start tick() again
}

这很好,因为它是无限动画。我将 console.log("hello") 放在 tick 函数中,然后每次执行该函数时,都会将“hello”一词写入控制台。到目前为止,一切都很好 !。当我更改 Controller 时,即当我单击转到第2页时,我之前的动画仍在运行,并且我仍然可以看到第一个 Controller 中的函数的console.log(“hello”)。

更换 Controller 后如何停止此功能?

这是我的代码:

http://plnkr.co/edit/66cK7gWTNQNh4vmC2lmp?p=preview

最佳答案

监听被破坏的范围并停止动画循环:

function MyController($scope) {
  var animating = true;
  $scope.$on('$destroy', function () {
    animating = false;
  });

  function tick() {
    if (!animating) return;
    console.log("hello");
  }
}

在此处了解 Angular 的范围 $destroy 事件:https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$destroy

关于javascript - 当我访问另一个状态时停止一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46740714/

相关文章:

javascript - 如何正确使用 indexOf() 处理多个元素?

jquery - 如何在 Angular 服务中使用 jQuery.cookie 插件

angularjs - 如何访问 Angular 端的nodejs配置参数?

javascript - AngularJS ng-class 过滤器不起作用

javascript - Shopify,TypeError : $(. ..).jcarousel 不是函数

javascript - 修复 AWS API 网关和放大中不存在的 CORS "Response to preflight..." header

javascript - 为什么 React 会以不变的状态一遍又一遍地渲染我的组件?

javascript - 搜索##anything## 的所有实例

javascript - 如何正确测试 AngularJS Controller 功能

javascript - 防止击中子状态 ui-router