Gor
Gor

Reputation: 2908

AngularJS $interval stops automatically

I am using angularJS in my app. I have timer with $interval. When I open browser, it works, but sometimes it`s stops.
I tried these cases:

In these cases all work well, but when I locked windows for 4 hours I found that timer stopped updating after an hour.

Also there are some cases that timer is being stopped when Windows is not locked, so can you help me with this issue?

function setTime() {
        var now = new Date(timeStamp);
        $scope.time = new Date(new Date( now.getTime() + (now.getTimezoneOffset()  60000)).getTime() + ($scope.timezoneOffset  60000));
        if (!_intervalId) {
            _intervalId = $interval(function () {
                var tempTime = new Date().getTime();
                timeStamp += (tempTime - currentTime) > 1100 || (tempTime - currentTime) < 900 ? 1000 : tempTime - _currentTime;
                _currentTime = tempTime;
                var now = new Date(timeStamp);
                $scope.time = new Date(new Date( now.getTime() + (now.getTimezoneOffset()  60000)).getTime() + ($scope.timezoneOffset  60000))
            }, 1000)
        }
    }

Upvotes: 1

Views: 462

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276266

Some browsers do a thing where they stop long running tasks to save battery. It's not really documented anywhere very well as far as I know. It's possible to configure it in some browsers, in everyone's favorite (sigh) IE - it's in windows power options:

enter image description here

So this is really happening, you're not losing your sanity. The browser is trying to conserve battery power on sites running long-running tasks.

I recommend you detect activity on the page (a mousemove for example) and restart the interval if it did update a counter you keep for this purpose in a second. Dirty but will likely work.

Upvotes: 1

Related Questions