我有两个 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 后如何停止此功能?
这是我的代码:
最佳答案
监听被破坏的范围并停止动画循环:
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/