angularjs $间隔被多次调用 [英] angularjs $interval being called multiple times

查看:111
本文介绍了angularjs $间隔被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内部控制我打电话$间隔每第二种秒表服务之后作一个函数调用。

但问题是,我回来的这台路由器被调用多次的功能,例如如果我去另一个菜单,然后回来这里..定时器将更换两次..如果我再做一遍,然后瞬间。

我曾尝试以下3种方法的航线所有相同的结果控制器:

  $超时(updateTimer,1000);的setInterval(函数(){$ $范围适用(updateTimer);},1000);$间隔(updateTimer,1000);

为什么叫很多次我回到这个页??

计时器

解决方案

ECH时间的路由被调用时,所述控制器assciated到该路由被实例化。而且你开始每个控制器实例化一个时间间隔。所以,你得到这个结果。

确认取消间隔当控制器不再使用。 ŧ他的官方文档有对这种情况中的特定警告,并举例说明了如何取消间隔一旦控制器不再使用:


  

请注意:此服务创建的间隔必须在使用完后明确销毁。特别是当一个控制器的范围或指令的元素被摧毁,他们不会自动销毁。你应该考虑到这一点,并确保始终在适当的时候取消间隔。请参阅下面的例子就如何以及何时做到这一点的更多细节。


  VAR停止= $间隔(...);$范围。在$('$破坏',函数(){
    //确保该区间被破坏过
    $ interval.cancel(停止);
});

inside controller i am calling $interval to make a function call after every second kind of stopwatch service.

but the problem is the function gets called as many times as i come back to this router, e.g. if i go to another menu and come back here.. the timer would be changed twice.. if i do it again then trice.

i have tried below 3 methods in route all with same result in the controller:

$timeout(updateTimer, 1000);

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

$interval(updateTimer, 1000);

why is the timer called as many times as i come back to this page??

解决方案

Ech time a route is called, the controller assciated to this route is instantiated. And you're starting an interval each time your controller is instantiated. So you get this result.

Make sure to cancel your interval when the controller is not used anymore. The official documentation has a specific warning about this situation, and an example showing how to cancel the interval once the controller isn't used anymore:

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 $间隔被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆