gpt4 book ai didi

angularjs $interval被多次调用

转载 作者:行者123 更新时间:2023-12-02 05:37:00 28 4
gpt4 key购买 nike

在 Controller 内部,我调用 $interval 以在每隔一种秒表服务后进行一次函数调用。

但问题是当我回到这个路由器时这个函数被调用了很多次,例如如果我转到另一个菜单然后回到这里.. 计时器将更改两次.. 如果我再做一次,那么会三次。

我在路由中尝试了以下 3 种方法,在 Controller 中的结果都相同:

$timeout(updateTimer, 1000);

setInterval(function () { $scope.$apply(updateTimer); }, 1000);

$interval(updateTimer, 1000);

为什么当我返回此页面时定时器被调用多次??

最佳答案

每次调用路由时,都会实例化与该路由关联的 Controller 。每次实例化 Controller 时,您都会开始一个间隔。所以你得到了这个结果。

确保在不再使用 Controller 时取消间隔。电话 he official documentation有一个关于这种情况的具体警告,以及一个示例,说明如何在不再使用 Controller 后取消间隔:

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.

var stop = $interval(...);

$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$interval.cancel(stop);
});

关于angularjs $interval被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22420817/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com