Within my agnularjs directive, I have an object containing the logic of a script:
$scope.slider = {
increment: 0,
step: 1,
positionTop: 0,
init: function (step, isClick) {
if(isClick) clearInterval($scope.interval);
...rest of script...
After closing $scope.slider
, I have the following code:
$timeout(function () {
$scope.slider.changeSlide($scope.slider.step);
$scope.interval = setInterval(function () {
$scope.slider.step++;
if($scope.slider.step === 5) $scope.slider.step = 1;
$scope.slider.changeSlide($scope.slider.step);
}, 5000);
});
Upon page load, I start the init
method and then allow users to trigger it by clicking on this html tag:
<span class="main__last-added-dot"
data-ng-class="slider.step == 1 ? 'main__last-added-dot--active' : ''"
data-ng-click="slider.init(1, true);"></span>
If the user clicks on the tag, it clears the interval and stops the process. However, setting a new interval becomes a challenge due to backend calls delaying the div elements gathering.
I attempted assigning the interval to another scope variable and calling it like so:
inside the init method within the $scope.slider
object:
$timeout(function(){ $scope.startInterval() });
below the $scope.slider
object:
$timeout(function () {
$scope.startInterval = function() {
$scope.interval = setInterval(function () {
console.log('fire function interval');
$scope.slider.step++;
if($scope.slider.step === 5) $scope.slider.step = 1;
$scope.slider.changeSlide($scope.slider.step);
}, 5000);
};
$scope.startInterval();
});
However, this setup seems to create a loop and behaves strangely. What am I doing wrong? How can I properly stop and restart the interval after clicking on the span element to reset seconds to 0?
A working demo can be found here.