1

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?

skmvasu
  • 3,098
  • 3
  • 24
  • 29

1 Answers1

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
  • Use $interval (check doc about that) not setInterval – Hotgeart Dec 03 '15 at 15:02