Home > Web Front-end > JS Tutorial > AngularJS timer cannot be stopped

AngularJS timer cannot be stopped

黄舟
Release: 2017-02-18 13:46:12
Original
1193 people have browsed it

1. Problem background

After setting the timer in AngularJS, click the button again to trigger the timer. At this time, it will appear: the previous timer has not stopped, and the next timer has not stopped. The timer is started again, resulting in multiple timers running at the same time.


##2. Problem source code

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>AngularJS之定时器无法停止</title>
		<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
		<script>
			var app = angular.module("btnApp",[]);
			app.controller("btnCon",function($scope,$interval){
				$scope.count = 0;
				$scope.getDayTime = function(){
					var date = new Date();
					var year = date.getFullYear();
					var month = date.getMonth()+1;
					var day = date.getDate();
					var hour = date.getHours();
					var minute = date.getMinutes();
					var second = date.getSeconds();
					var thisTime = year+"-"+(month<10?"0"+month:month)+"-"+(day<10?"0"+day:day)+" "+(hour<10?"0"+hour:hour)+":"+(minute<10?"0"+minute:minute)+":"+(second<10?"0"+second:second);
					
					return thisTime;
				};
				$scope.dayTime = $scope.getDayTime();
				$scope.queryData = function(){
					var timer = $interval(function(){  
	                    $scope.count++;  
	                    console.log($scope.count);
	                },4000);
	                
	                $scope.$on("destroy",function(){
					   $interval.cancel($scope.timer);
					}); 
				};
			});
		</script>
	</head>
	<body ng-app="btnApp">
		<p ng-controller="btnCon">
			<button ng-click="queryData();">查询</button>
			<p>
				<label>{{count}}</label>
			</p>
		</p>
	</body>
</html>
Copy after login


3. Question result



##4. Solved source code


5. Solved result

The above is the content that the AngularJS timer cannot be stopped. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template