2015-09-24 101 views
0

用我正在做一個控制器處理倒計時,像這樣:避免內存泄漏倒計時

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是正常的。

希望你能幫我防止這種行爲。

感謝

+0

真的需要一個秒計數器(甚至單分鐘),當最後期限是幾天? – charlietfl

+0

@charlietfl這是客戶端要求的:/ –

回答

1

什麼cancel$interval每當$destroy發生什麼呢?

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