javascript - 在 Angular.js 中显示多个计时器功能

标签 javascript angularjs timer

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

第一个计时器仅显示 5 秒,10 秒后我需要显示计时器 2。 我对 Angular 非常陌生,并编写了以下代码。

它似乎工作正常,除了第三次调用 settimeout 时它无法正常工作并且开始变得非常快。

Controller

 // 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>

最佳答案

您基本上启动了多个 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

关于javascript - 在 Angular.js 中显示多个计时器功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586005/

相关文章:

javascript - 如何添加 AJAX 操作 - Elgg

javascript - `yarn link` 和 `npm link` 有什么区别?

php - Laravel Blade 的 json 输出对象带有单引号?

Flash AS3 Timer 极度关闭

Python:threading.timer 不遵守间隔

java - 需要计时器或其他想法来允许代码在调用方法和 JOptionPane 后继续执行

javascript - Rails - Javascript 不会通过 link_to 渲染,但通过正常的创建操作可以正常工作

javascript - 我可以在 golang 中定义/拼凑一个 javascript 类吗?

javascript - 为什么我们在 Angular 上将 Controller 变量设置为 "this"?

javascript - AngularJS 中的动态 http post 参数名称