記錄一下使用$interval遇到的坑

記錄一下使用$interval遇到的坑

當在angular controller中用到了$interval,則必須在特定時間手動清楚定時器,不然該定時器將會一直執行下去。函數

$interval.cancel( timer );

若是但願在該DOM從頁面上移除時,中止該定時器code

$scope.$on( "$destroy", function() {  $interval.cancel( timer ); } );

完整實例說明事件

// 定時器 定時刷新數據
var timer = $interval(
  function() {
    hello();//本身定義的每次須要執行的函數,也能夠寫一些其餘的內容
  },
  5000
);
//當DOM元素從頁面中被移除時,AngularJS將會在scope中觸發$destory事件。
//這讓咱們能夠有機會來cancel任何潛在的定時器。切換controller、頁面後便可調用
$scope.$on(
  "$destroy",
  function() {
    $interval.cancel( timer );
  }
);
相關文章
相關標籤/搜索