1. Problem background
Set a timer, given two variables startData and endData, subtract 5 and 50 respectively after the timer starts; click Stop to pause After the timer is reset, the data will be restored to the original data.
2. Implementation source code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>AngularJS停止定时器</title> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script> var app = angular.module("intervalApp",[]); app.controller("intervalController",["$scope","$interval",function($scope,$interval){ $scope.startData = 100; $scope.endData = 1000; var stopEvent; $scope.startEvent = function(){ if(angular.isDefined(stopEvent)) return; stopEvent = $interval(function(){ if($scope.startData > 50 && $scope.endData > 500) { $scope.startData = $scope.startData - 5; $scope.endData = $scope.endData - 50; } else { $scope.stopClick(); } },1000) }; $scope.stopClick = function(){ if(angular.isDefined(stopEvent)) { $interval.cancel(stopEvent); stopEvent = undefined; } }; $scope.resetEvent = function(){ $scope.startData = 100; $scope.endData = 1000; }; $scope.$on("$destory",function(){ $scope.stopClick(); }); }]); </script> </head> <body ng-app="intervalApp"> <p ng-controller="intervalController"> <button data-ng-click="startEvent()">开始</button> <button data-ng-click="stopClick()">停止</button> <button data-ng-click="resetEvent()">重置</button><br> <p>开始数据:{{startData}}</p><br> <p>结束数据:{{endData}}</p><br> </p> </body> </html>
3. Implementation results
(1) Initialization
(2) Click Start
(3) Click Stop
(4) Click Reset
## The above is the content, please pay attention to more related content PHP Chinese website (www.php.cn)!