I am trying to debate whether this is a good method of handling timers in Javascript. I am using Angular, but the concept is the same as using setTimeout
instead of the $timeout
function Angular provides.
Old method:
$scope.timer=$scope.doTiming();
$scope.timeRemaining=30; //30 second timer;
$scope.doTiming=function(){
return $timeout(function(){
$scope.timeRemaining=$scope.timeRemaining-1;
if($scope.timeRemaining<=0){
$scope.disabledEntry=true;
$scope.submitData();
}else{
$scope.timer=$scope.doTiming();
}
},1000);
};
Time elapsed on a 30 timer: 30.050 seconds
New Method:
var startTime=new Date().getTime, delta; //new: get current time
$scope.timeRemaining=30;
$scope.timer=$scope.doTiming();
$scope.doTiming=function(){
return $timeout(function(){
delta=(new Date().getTime())-startTime; //new: get delta from start time
$scope.timeRemaining=$scope.timeRemaining-(delta/1000); //new: subtract by delta
if($scope.timeRemaining<=0){
$scope.disabledEntry=true;
$scope.submitData();
}else{
$scope.timer=$scope.doTiming();
}
},1);
};
Time elapsed on a 30 timer: 30.002 seconds
Major difference is that the old way looped every second, and ticked down the timer. The new way loops constantly very quickly and measures the time based on the change in time from the start, so it has the potential to be more accurate. I am wondering if this is reasonable or not? Is this type of instant loop going to cause issues on older computers? Should I maybe use the new way with a timer of 100 instead of 1? Thoughts?
EDIT
The new way is preferable to me for reasons associated with slowed timeouts: Chrome: timeouts/interval suspended in background tabs?