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

时间:2015-03-23 02:29:13

标签: javascript angularjs timer difference stopwatch

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

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

最简单的方法是什么?

2 个答案:

答案 0 :(得分:1)

扩展我上面的评论,就像这样......

var startTime = new Date();
$scope.stopwatch = 0;

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

并在您的模板中

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

创建用于格式化hh:mm:ss格式的秒数的过滤器的加分点。

答案 1 :(得分:0)

实现这一目标的最佳方法是使用$ 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);
    }
}