angularjs计算开始时间和当前时间之间的时间差

angularjs calculate time difference between start time and current time

本文关键字:时间 之间 时间差 计算 开始 开始时 angularjs      更新时间:2023-09-26

我正试图在AngularJS应用程序中创建类似于秒表的东西。

我有一个"开始"按钮,当单击该按钮时,应用程序将设置一个获取当前时间的startTime变量,然后我想要另一个每秒更新一次的变量,并计算startTime变量和当前时间之间的秒差,我可以将其用作显示给用户的秒表值。我还需要能够停止和重新启动计时器,所以我希望秒表值以秒为单位存储,这样我就可以轻松地在任何秒数启动计时器并恢复计时器。

做这件事最简单的方法是什么?

在我上面的评论的基础上,类似于。。。

var startTime = new Date();
$scope.stopwatch = 0;
$interval(function() {
    $scope.stopwatch = (new Date() - startTime) / 1000;
}, 1000);

以及在您的模板中

<p>Seconds: {{ stopwatch }}</p>

创建一个以hh:mm:ss格式格式化秒的过滤器可获得额外积分。

实现这一点的最佳方法是使用$interval,如下所示:

var stop, seconds=0;
stop = $interval(updatingFunc, 1000);
function updatingFunc(){
    seconds++;
    console.log(seconds);
    if(seconds === 4){ // Here you set whatever condition to cancel the interval
        $interval.stop(stop);
    }
}