I'm writing a small quiz application where I need to display a timer the elapsed time to the user. I don't see any wrapper for the setInterval(). using window.setInterval looks awkward. Is there a clean Angular way of updating the time?
-
4Near same question, exact same answer: stackoverflow.com/questions/14237070/…Philipp Gayret– Philipp Gayret2013-10-07 12:42:07 +00:00Commented Oct 7, 2013 at 12:42
-
1@see siddii.github.io/angular-timerDennis Jaamann– Dennis Jaamann2013-10-07 14:23:06 +00:00Commented Oct 7, 2013 at 14:23
-
@Philipp - I saw that post too, but that solution looked anti semantic. I just wanted to know if a better a solution exist.skmvasu– skmvasu2013-10-08 11:04:39 +00:00Commented Oct 8, 2013 at 11:04
-
Nope, however you could also do a setInerval with scope.$apply in it, $timeout just doesn't have an inteval method, only timeout.Philipp Gayret– Philipp Gayret2013-10-08 11:30:26 +00:00Commented Oct 8, 2013 at 11:30
Add a comment
|
1 Answer
I would suggest to wrap the 'awkward' code in some helper module. Remember to $apply() your changes so AngularJS can update the bindings.
// helper code
var applyIfPossible = function (scope, fn) {
if (!scope.$root.$$phase) {
scope.$apply(function () {
fn();
});
} else {
fn();
}
};
function setupInterval(scope, timeSpanInMilliseconds) {
var intervalHandler = window.setInterval(function(){
applyIfPossible(scope, intervalCallbackFn);
}, timeSpanInMilliseconds);
var unregisterDestroyHandler = null;
unregisterDestroyHandler = scope.$on('$destroy', ()=> {
window.clearInterval(intervalHandler);
unregisterDestroyHandler();
});
scope = null;
return function clearInterval() {
unregisterDestroyHandler();
window.clearInterval(intervalHandler);
}
}
// app code
var stopInterval = setupInterval(scope, 200, update); // update does you repeated stuff
// later on
stopInterval();
2 Comments
skmvasu
I thought about this, but this still looks messy. And BTW, you need to make sure to call cancelInterval() when the view is destroyed. Otherwise this method will keep executing even after you move out of this scope.
Hotgeart
Use $interval (check doc about that) not setInterval