Skip to content
This repository has been archived by the owner on May 29, 2019. It is now read-only.

fix(carousel): cancel timer on scope destroyed #1451

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions src/carousel/carousel.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,23 +103,32 @@ angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition'])
};

$scope.$watch('interval', restartTimer);
$scope.$on('$destroy', resetTimer);

function restartTimer() {
resetTimer();
var interval = +$scope.interval;
if (!isNaN(interval) && interval>=0) {
currentTimeout = $timeout(timerFn, interval);
}
}

function resetTimer() {
if (currentTimeout) {
$timeout.cancel(currentTimeout);
currentTimeout = null;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chrisirhc You should also extract this code:

if (currentTimeout) {
      $timeout.cancel(currentTimeout);
      currentTimeout = null;
}

into its own function as it is called multiple times.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. I'll do that when I wake heh. Just about to sleep.
Update: Just did it.

function go() {
if (isPlaying) {
$scope.next();
restartTimer();
} else {
$scope.pause();
}
}
var interval = +$scope.interval;
if (!isNaN(interval) && interval>=0) {
currentTimeout = $timeout(go, interval);
}

function timerFn() {
if (isPlaying) {
$scope.next();
restartTimer();
} else {
$scope.pause();
}
}

$scope.play = function() {
if (!isPlaying) {
isPlaying = true;
Expand All @@ -129,9 +138,7 @@ angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition'])
$scope.pause = function() {
if (!$scope.noPause) {
isPlaying = false;
if (currentTimeout) {
$timeout.cancel(currentTimeout);
}
resetTimer();
}
};

Expand Down Expand Up @@ -163,6 +170,7 @@ angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition'])
currentIndex--;
}
};

}])

/**
Expand Down
14 changes: 14 additions & 0 deletions src/carousel/test/carousel.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,20 @@ describe('carousel', function() {
expect(ctrl.slides.length).toBe(1);
expect(ctrl.currentSlide).toBe(ctrl.slides[0]);
});

it('issue 1414 - should not continue running timers after scope is destroyed', function() {
spyOn(scope, 'next').andCallThrough();
scope.interval = 2000;
scope.$digest();

$timeout.flush();
expect(scope.next.calls.length).toBe(1);

scope.$destroy();

$timeout.flush(scope.interval);
expect(scope.next.calls.length).toBe(1);
});
});
});
});