zoukankan      html  css  js  c++  java
  • AngularJS之定时器无法停止

    1、问题背景

         AngularJS设置定时器后,再次点击按钮触发定时器,这时会出现:前一个定时器未停止,后一个定时器又启动了,导致出现多个定时器同时在运行。


    2、问题源码

    <!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">
    		<div ng-controller="btnCon">
    			<button ng-click="queryData();">查询</button>
    			<div>
    				<label>{{count}}</label>
    			</div>
    		</div>
    	</body>
    </html>
    

    3、问题结果


    4、解决源码


    5、解决结果


  • 相关阅读:
    01_垂直居中body中的应用
    C++基础知识易错点总结(2)
    辗转相除求最大公约数
    C++基础知识易错点总结(1)
    类对象的建立方式总结
    LeetCode(131)Palindrome Partitioning
    基本套接字编程(7) -- udp篇
    LeetCode(124) Binary Tree Maximum Path Sum
    LeetCode(115) Distinct Subsequences
    LeetCode(97) Interleaving String
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13314074.html
Copyright © 2011-2022 走看看