我有这个angularJS应用程序,它有一个倒数计时器。我想在它变为零后执行一个函数。它目前在达到0后变为负数。如何实现这一点?
Angular Code:
myApp.controller('MyController', ['$scope', '$timeout' ,function($scope, $http, $routeParams, $timeout) {
$scope.counter = 5000;
$scope.onTimeout = function(){
$scope.counter--;
mytimeout = $timeout($scope.onTimeout,1000);
}
var mytimeout = $timeout($scope.onTimeout,1000);
}
}]);
testControllers.filter('formatTimer', function() {
return function(input)
{
function z(n) {return (n<10? '0' : '') + n;}
var seconds = input % 60;
var minutes = Math.floor(input / 60);
var hours = Math.floor(minutes / 60);
return (z(hours) +':'+z(minutes)+':'+z(seconds));
};
});
HTML:
<div><p>{{counter|formatTimer}}</p></div>
答案 0 :(得分:3)
当计数器为0时,只需停止调用它:
$scope.onTimeout = function(){
if (--$scope.counter > 0) {
$timeout($scope.onTimeout, 1000);
} else {
// Call your function now that counter is 0
}
}
答案 1 :(得分:0)
根据您正在做的其他事情,您可能不需要将超时方法放在范围上。另外,请查看$ interval。它更适合连续呼叫。
function decreaseCounter() {
if(--$scope.counter <= 0) {
$interval.cancel(intervalPromise);
yourOtherFunction();
}
}
var intervalPromise = $interval(decreaseCounter, 1000);
答案 2 :(得分:0)
如果您需要精确倒计时(特别是如果时间跨度很大),您需要计算使用日期时间功能所花费的时间。简单地每1000毫秒增加一个计数器5000次,doesen不保证最后花费的实际时间恰好是5000秒!
您可以尝试这样的事情:
控制器:
function MyCtrl($scope, $interval) {
var intervalId;
$scope.counter = 0;
$scope.initialCountdown = 10;
$scope.countdown = $scope.initialCountdown;
$scope.timer = function(){
var startTime = new Date();
intervalId = $interval(function(){
var actualTime = new Date();
$scope.counter = Math.floor((actualTime - startTime) / 1000);
$scope.countdown = $scope.initialCountdown - $scope.counter;
}, 1000);
};
$scope.$watch('countdown', function(countdown){
if (countdown === 0){
$scope.stop();
}
});
$scope.start = function(){
$scope.timer();
};
$scope.stop = function(){
$interval.cancel(intervalId);
};
}
查看:
<div ng-controller="MyCtrl">
<div>Counter: {{counter}}</div>
<div>Countdown in seconds: {{countdown}}</div>
<div>Countdown date time: {{countdown | secondsToDateTime | date:'HH:mm:ss'}}</div>
<button ng-click="start()">start</button>
<button ng-click="stop()">stop</button>
</div>
myApp.filter('secondsToDateTime', [function() {
return function(seconds) {
return new Date(1970, 0, 1).setSeconds(seconds);
};
}])
享受!