How to use setInterval on Angularjs -


this question has answer here:

i'm writing small quiz application need display timer elapsed time user. don't see wrapper setinterval(). using window.setinterval looks awkward. there clean angular way of updating time?

i suggest wrap 'awkward' code in helper module. remember $apply() changes angularjs can update 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 repeated stuff  // later on stopinterval(); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -