gpt4 book ai didi

javascript - AngularJS 计时器代码不会执行所有 if else 条件

转载 作者:行者123 更新时间:2023-12-02 16:27:42 25 4
gpt4 key购买 nike

我遇到了 if else 条件的问题。我设计了一个计时器,在四种情况下在控制台上显示不同的消息;但是,这些消息仅在控制台上显示前两条消息。不会去第三和第四。它有什么问题呢?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('TimeCtrl', ['$scope' , '$timeout', function ($scope , $timeout) {
$scope.today = new Date();

$scope.seconds = 0;
$scope.max = 10;
var stopped;

$scope.stopTimer = function(){
$timeout.cancel(timer);

};
$scope.start = function(){

timer = $timeout(function(){
$scope.seconds++;
console.log($scope.seconds);
if ($scope.seconds < 20) {
$scope.start();
if ( $scope.seconds < 5) {
//blue
console.log('progress-info');
}else if ( 5 <= $scope.seconds < 10 ) {
//green
console.log('progress-success');
}else if ( 10 <= $scope.seconds < 15 ) {
//yellow
console.log('progress-warning');
}else if ( 15 <= $scope.seconds < 20){
//red
console.log('progress-danger');
};
}else{
$scope.stopTimer();
}

},1000)

};

}]);

</script>
</head>
<body>

<div ng-app="myApp" ng-controller="TimeCtrl">
<button ng-click="start()">start</button>
<button ng-click="stopTimer()">stop</button>
current time {{seconds}}
</div>

</body>

最佳答案

问题是

else if ( 5 <= $scope.seconds < 10 )

如果 5 <= 秒,JavaScript 将首先测试这一点。如果为 true,则条件为 true,并且下一个评估为

true < 10

在这种情况下,javascript 将 true 视为 1,因此这将计算为 true,并且将执行 if block 。

因此,您期望如果 $scope.seconds = 11,则此语句不会成立,但是:

5 <= 11 -> true -> 1,然后 1 < 10 -> true,因此 block 执行

要解决此问题,请将 if 语句更改为:

if(5 <= $scope.seconds && $scope.seconds < 10)

此外,值得注意的是,您的变量“timer”不是用“var”声明的,因此您实际上是在设置 window.timer - 不建议。

myApp.controller('TimeCtrl', ['$scope' , '$timeout', function ($scope , $timeout) {
$scope.today = new Date();

$scope.seconds = 0;
$scope.max = 10;
var stopped;
var timer; //declare timer so it won't be global

$scope.stopTimer = function(){
$timeout.cancel(timer);

};
$scope.start = function(){

timer = $timeout(function(){
$scope.seconds++;
console.log($scope.seconds);
if ($scope.seconds < 20) {
$scope.start();
if ( $scope.seconds < 5) {
//blue
console.log('progress-info');
}else if ( 5 <= $scope.seconds < 10 ) {
//green
console.log('progress-success');
}else if ( 10 <= $scope.seconds < 15 ) {
//yellow
console.log('progress-warning');
}else if ( 15 <= $scope.seconds < 20){
//red
console.log('progress-danger');
};
}else{
$scope.stopTimer();
}

},1000)

};

}]);

关于javascript - AngularJS 计时器代码不会执行所有 if else 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28554159/

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