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?
Asked
Active
Viewed 6,091 times
1
-
4Near same question, exact same answer: http://stackoverflow.com/questions/14237070/using-setinterval-in-angularjs-factory/14238039#14238039 – Philipp Gayret Oct 07 '13 at 12:42
-
1@see http://siddii.github.io/angular-timer/ – Dennis Jaamann Oct 07 '13 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 Oct 08 '13 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 Oct 08 '13 at 11:30
1 Answers
1
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();

Benjamin
- 1,165
- 7
- 19
-
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. – skmvasu Oct 08 '13 at 11:02
-