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?

4
  • 4
    Near same question, exact same answer: stackoverflow.com/questions/14237070/… Commented Oct 7, 2013 at 12:42
  • 1
    @see siddii.github.io/angular-timer Commented 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. Commented 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. Commented Oct 8, 2013 at 11:30

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Use $interval (check doc about that) not setInterval

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.