【问题标题】:Avoid memory leak with angular's $interval used in countdown在倒计时中使用 Angular 的 $interval 避免内存泄漏
【发布时间】:2015-09-24 19:02:53
【问题描述】:

我正在做一个处理倒计时的控制器,如下所示:

var addzero;

addzero = function(number) {
  if (number < 10) {
    return '0' + number;
  }
  return number;
};

angular.module('theapp').controller('TematicCountdownController', [
  '$scope', '$timeout', function($scope, $timeout) {
    var intervalPromise;
    return intervalPromise = $timeout((function() {

      var days, daysRound, deadline, hours, hoursRound, minutes, minutesRound, now, seconds, secondsRound;

      now = new Date;
      deadline = new Date('oct 5 2015 00:00:00');

      days = (deadline - now) / 1000 / 60 / 60 / 24;
      daysRound = Math.floor(days);
      $scope.dd = daysRound;

      hours = (deadline - now) / 1000 / 60 / 60 - (24 * daysRound);
      hoursRound = Math.floor(hours);
      $scope.hh = addzero(hoursRound);

      minutes = (deadline - now) / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
      minutesRound = Math.floor(minutes);
      $scope.mm = addzero(minutesRound);

      seconds = (deadline - now) / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
      secondsRound = Math.round(seconds);
      $scope.ss = addzero(secondsRound);

    }), 1000);
  }
]);

任务管理器告诉我,我的 Angular 应用程序的进程越来越消耗更多的内存,并且不断使用 CPU。

在实施这个倒计时之前,内存使用和 CPU 是正常的。

希望你能帮助我防止这种行为。

谢谢

【问题讨论】:

  • 距离截止日期还有几天真的需要秒计数器(甚至是一分钟)吗?
  • @charlietfl 那是客户要求的:/

标签: javascript angularjs memory-leaks


【解决方案1】:

每当$destroy 发生时,cancel$interval 怎么样?

$scope.$on('$destroy', function() {
  $interval.cancel(intervalPromise);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-22
    • 2016-03-29
    • 2018-04-08
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多