【问题标题】:Showing multiple timer function in Angular.js在 Angular.js 中显示多个计时器功能
【发布时间】:2017-10-05 12:47:42
【问题描述】:

我正在尝试在具有不同开始时间的网页上显示两个计时器。

第一个计时器只显示 5 秒,然后在 10 秒后我需要显示 timer2。 我对 Angular 很陌生,并整理了以下代码。

它似乎工作正常,除非当第三次调用 settimeout 时它不能正常工作并且开始非常快。

控制器

 // initialise variables
$scope.tickInterval = 1000; //ms
var min ='';
var sec ='';

$scope.ti = 0;
$scope.startTimer1 = function() {
    $scope.ti++;
    min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
    sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
    $scope.timer1 =  min + ":" + sec;
    mytimeout1 = $timeout($scope.startTimer1, $scope.tickInterval); // reset the timer
}

//start timer 1
$scope.startTimer1();

$scope.$watch('timer1',function(){

    if($scope.timer1 !=undefined){
        if($scope.timer1 =='00:05'){
            $timeout.cancel(mytimeout1);
            setInterval(function(){

                $scope.startTimer2()
                $scope.ti = 0;

            },1000)
        }
    }

})

//start timer 2 after 2 mins and 20 seconds
$scope.startTimer2 = function() {
    $scope.ti++;
    min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
    sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
    $scope.timer2 =  min + ":" + sec;
    mytimeout2 = $timeout($scope.startTimer2, $scope.tickInterval);
}


$scope.$watch('timer2',function(){

    if($scope.timer2 !=undefined){
        if($scope.timer2 =='00:05'){

            $timeout.cancel(mytimeout2);

            setInterval(function(){

                $scope.startTimer1();
                $scope.ti = 0;

            },1000)


        }
    }

})

在我看来,我只是有

<p>{{timer1}}</p>

<p>{{timer2}}</p>

【问题讨论】:

  • 你不应该使用 setInterval 而应该使用 $interval。

标签: javascript angularjs timer


【解决方案1】:

你基本上是在启动多个 startTimer 函数,所以它会加起来。如果我很好地理解了您的问题,您甚至不需要所有这些观察者和超时。 你可以这样使用 $interval :

$scope.Timer = $interval(function () {

  ++$scope.tickCount

  if ($scope.tickCount <= 5) {
    $scope.timer1++
  } else {
    $scope.timer2++
    if ($scope.tickCount >= 10)
        $scope.tickCount = 0;
  }
}, 1000);

工作fiddle

【讨论】:

  • 谢谢,但我需要以分:秒格式显示两个“计数”计时器。当第一个计时器到达 02:00 时,它需要停止/暂停,第二个计时器应该从 00:01 开始。一旦第二个计时器到达 02:00,它就会暂停,然后第一个计时器再次循环。所以我用的是手表。
  • 检查新的小提琴,它应该是你要找的 - 请注意,我没有格式化计时器,但你可以使用整数上的代码示例将其格式化为 mm:ss
  • 感谢您向我展示如何有效地解决我的问题。
猜你喜欢
  • 2016-12-24
  • 2022-10-18
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多