在倒计时中使用角度的$间隔避免内存泄漏

时间:2015-09-24 19:02:53

标签: javascript angularjs memory-leaks

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

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);
  }
]);

任务管理器告诉我,我的角度应用程序的过程越来越多地消耗更多的内存,CPU也在不断使用。

在实施此倒计时之前,内存使用率和CPU正常。

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

由于

1 个答案:

答案 0 :(得分:1)

{{ questions.0 }}发生cancel$interval会怎样?

$destroy