diff --git a/src/carousel/carousel.js b/src/carousel/carousel.js index cb7d585173..854b3b6fe4 100644 --- a/src/carousel/carousel.js +++ b/src/carousel/carousel.js @@ -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; } - 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; @@ -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(); } }; @@ -163,6 +170,7 @@ angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition']) currentIndex--; } }; + }]) /** diff --git a/src/carousel/test/carousel.spec.js b/src/carousel/test/carousel.spec.js index 0bea1d3daa..78d41699c3 100644 --- a/src/carousel/test/carousel.spec.js +++ b/src/carousel/test/carousel.spec.js @@ -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); + }); }); }); });