gpt4 book ai didi

javascript - Angular 中的倒计时,并重新启动

转载 作者:行者123 更新时间:2023-12-01 03:29:09 27 4
gpt4 key购买 nike

我创建了一个简单的仪表板,其中包含一些数据作为 Angular 中的试用。通过 PHP,我获得了一些天气数据、通过 Google 新闻获得的新闻以及关于某个关键字的 10 条推文。

使用 $interval,我每 10 秒刷新一次仪表板,但我想要从 10 到 0 的倒计时,当触发间隔时,倒计时会一遍又一遍地开始。

有人可以帮助我实现这个目标吗?

当前代码作为提交按钮和 $interval 触发器:

$scope.formSubmit = function(){ 
$scope.getResults();
if($scope.interval){
intervalController();
}
}

function intervalController(){
$interval($scope.getResults, 10000);
}

$scope.getResults = function(){
if($scope.city){
$http({
method: 'POST',
url: 'server.php',
data: {city : $scope.city}
}).then(function successCallback(response){
console.log(response.data);
//some data processing here
}, function errorCallback(response){

})
}
}

最佳答案

$scope.initialCountDownValue = 10;
$scope.countDownValue = $scope.initialCountDownValue;
var intervalCanceller = null;

$scope.formSubmit = function(){
$scope.getResults();
if($scope.interval){
intervalController();
}
}


function decrementCountdown() {
$scope.countDownValue -= 1;
if ( $scope.countDownValue === 0) {
$scope.getResults();
$scope.countDownValue = $scope.initialCountDownValue;
}
}

function intervalController(){
intervalCanceller = $interval(decrementCountdown, 1000);
}

$scope.getResults = function(){
if($scope.city){
$http({
method: 'POST',
url: 'server.php',
data: {city : $scope.city}
}).then(function successCallback(response){
console.log(response.data);
//some data processing here
}, function errorCallback(response){

})
}
}

$scope.countDownValue 中,您可以向用户显示倒计时值。

还有一点。

不要忘记取消订阅范围销毁的 $interval。或者你将有一段时间,永远白白地活着。以下是正确破坏间隔的方法:

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

关于javascript - Angular 中的倒计时,并重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44638710/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com