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"> <p ng-controller="btnCon"> <button ng-click="queryData();">查询</button> <p> <label>{{count}}</label> </p> </p> </body> </html>
4、解源碼
5、解決結果
以上是AngularJS之定時器無法停止的內容,更多相關內容請關注PHP中文網(m.sbmmt.com)!