1

I am in a spot where I need to poll my server for data every so often. I have looked around at how people are handling this in angularjs and I am pretty confused.

Some examples are of just simple counters that increment up/down. Other are using the $timeout service. I need the ability to turn this on/off with a button click. I.E. click to start poll, poll every 30 seconds, click button to stop polling.

1 Answer 1

1

I am not claiming to be great at javascript nor angular so please go easy. I did write my own service that uses setInterval and clearInterval:

angular.module('myModule', [])
  .factory('TimerService',
    function () {
      var timers = {};

      var startTimer = function(name, interval, callback) {
        // Stop the timer if its already running, no-op if not running
        stopTimer(name);

        timers[name] = setInterval(function() {
          callback();
        }, interval);

        // Fire right away, interval will fire again in specified interval
        callback();
      }


      var stopTimer = function(name) {
        var timer = timers[name];
        if (timer) {
          clearInterval(timer);
          delete timers[name];
        }
      }

      return {
        start: startTimer,
        stop: stopTimer
      };
    });

Then in my controller I do this:

  var timerARunning = false;
  $scope.onClickA = function() {
    var timerName = 'timerA';
    timerARunning = !timerARunning;

    if (timerARunning) {
      TimerService.start(timerName, 5000, function() {
         alert("Timer A just fired");
      });
    } else {
      TimerService.stop(timerName);
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.