Rumah >hujung hadapan web >tutorial js >AngularJS停止定时器
1、问题背景
设置一个定时器,给定两个变量startData和endData,计时开始后分别减去5和50;单击停止暂停定时器,重置后数据恢复到原来的数据。
2、实现源码
<!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、实现结果
(1)初始化
(2)点击开始
(3)点击停止
(4)点击重置
以上就是的内容,更多相关内容请关注PHP中文网(www.php.cn)!