I'm trying to display a live time elapsed on a page
So I have this function which calculates the exact time elapsed to the second, and when called, it updates the HTML node with this time. It seems woefully inefficient to use a setInterval to call this function every second to update the display. Can anyone suggest a better solution? Many thanks
$scope.getAge = function(){
var today = new Date();
var birthDate = new Date("1980-05-30T04:00:00");
var bdInMilis = birthDate.getTime();
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);
var ageNode = document.getElementById("age-node");
if(ageNode){
ageNode.innerHTML = ("I am "+numyears+ " years, " + numdays + " days, " + numhours + " hours, " + numminutes + " minutes, " + numseconds + " seconds old (give or take)");
// can't keep doing this calculation every second
//$scope.refreshTime();
}
};