现场展示

时间:2015-08-06 13:16:54

标签: javascript html angularjs

我试图显示页面上的实时时间

所以我有这个函数来计算第二次经过的确切时间,当被调用时,它会用这个时间更新HTML节点。使用setInterval每秒调用此函数来更新显示效果似乎非常低效。有谁能建议更好的解决方案?非常感谢

notice

1 个答案:

答案 0 :(得分:0)

如果你想要使用setInterval一段时间比使用超时(check this

更好

此外,您还在使用angularjs,不要将您的字符串与innerHTML绑定。

<div>{{age}}</div>
...
$scope.getAge = function(){
    var today = new Date();
    var birthDate = new Date("1980-05-30T04:00:00");
    var bdInMilis = birthDate.getTime(); 

    setInterval(function(){
        var todayInMilis = today.getTime();
        var timeAlive = todayInMilis - bdInMilis;
        timeAlive = timeAlive/1000;
        var numyears = Math.floor(timeAlive / 31536000);
        var numdays = Math.floor((timeAlive % 31536000) / 86400); 
        var numhours = Math.floor(((timeAlive % 31536000) % 86400) / 3600);
        var numminutes = Math.floor((((timeAlive % 31536000) % 86400) % 3600) / 60);
        var numseconds = Math.floor((((timeAlive % 31536000) % 86400) % 3600) % 60);
        $scope.age = "I am "+numyears+ " years, " + numdays + " days, " + numhours + " hours, " + numminutes + " minutes, " + numseconds + " seconds old (give or take)";
    },1000);
};