AngularJS – 如何从00:00:00格式开始制作秒表

前端之家收集整理的这篇文章主要介绍了AngularJS – 如何从00:00:00格式开始制作秒表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建一个秒表.我用Google搜索并获得了一些关于如何制作计时器的提示.这是我在我的控制器中所做的:
$scope.value = 0;
$scope.startTimer = function() {

     $scope.value = 0;

    var change = function() {
        $scope.value += 1000;
        $timeout(change,1000);
    };
    $timeout(change,1000);
}

并以我的html显示这种格式的值:

<label>{{value | date: 'hh:mm:ss'}}</label>

问题是时钟始终在04:00:00开始,当我调用startTimer()函数时,它启动计时器没问题,但我希望计时器如下:

00:00:00

00:00:01

00:00:02

….

谁能告诉我如何在00:00:00启动计时器?

已编辑:使用间隔计时器更新了代码,因此现在代码包含$timeout和$interval的计时器.
在这里,你自己做过滤器:
var app = angular.module("myApp",[]);
app.controller("myController",function($scope,$timeout,$interval){
   
   //timer with timeout
   $scope.timerWithTimeout = 0;
   $scope.startTimerWithTimeout = function() {
    $scope.timerWithTimeout = 0;
    if($scope.myTimeout){
      $timeout.cancel($scope.myTimeout);
    }
    $scope.onTimeout = function(){
        $scope.timerWithTimeout++;
        $scope.myTimeout = $timeout($scope.onTimeout,1000);
    }
    $scope.myTimeout = $timeout($scope.onTimeout,1000);
  };
  
  $scope.resetTimerWithTimeout = function(){
    $scope.timerWithTimeout = 0;
    $timeout.cancel($scope.myTimeout);
  }
  
  //timer with interval
  $scope.timerWithInterval = 0;
   $scope.startTimerWithInterval = function() {
    $scope.timerWithInterval = 0;
    if($scope.myInterval){
      $interval.cancel($scope.myInterval);
    }
    $scope.onInterval = function(){
        $scope.timerWithInterval++;
    }
    $scope.myInterval = $interval($scope.onInterval,1000);
  };
  
  $scope.resetTimerWithInterval = function(){
    $scope.timerWithInterval = 0;
    $interval.cancel($scope.myInterval);
  }
})
app.filter('hhmmss',function () {
  return function (time) {
    var sec_num = parseInt(time,10); // don't forget the second param
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    var time    = hours+':'+minutes+':'+seconds;
    return time;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
  <label>Timer with timeout: {{timerWithTimeout | hhmmss}}</label>
  <button ng-click="startTimerWithTimeout()">Start Timer</button>
  <button ng-click="resetTimerWithTimeout()">reset tiemr</button>
  <br><br>
  <label>Timer with interval: {{timerWithInterval | hhmmss}}</label>
  <button ng-click="startTimerWithInterval()">Start Timer</button>
  <button ng-click="resetTimerWithInterval()">reset tiemr</button>
</div>

增加:对于计时器,最好使用$interval而不是$timeout.并始终将$interval引用到某个变量:$scope.timer = $interval(change,1000);,所以你可以在每次重置时销毁它:$interval.cancel($scope.timer); .

猜你在找的Angularjs相关文章