Adjust the interval scope within an AngularJS directive to set up a loop

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.

Answer №1

If you are looking for a solution, consider implementing the following code snippet. Additionally, feel free to refer to this functional plunker example that matches your specific requirements.

Custom Directive:

app.directive('myElement', ['$interval', '$timeout',
  function($interval, $timeout) {
    return {
      restrict: 'E',
      templateUrl: 'template.html',
      link: function(scope) {
        scope.timer=5000;
        scope.step = 1;
        function updateTime() {
          if(scope.step==4) scope.step=0;
          scope.step++;
        }
        scope.stopTime = $interval(updateTime, scope.timer);
        scope.resetTimer=function(step){
          scope.step = step;
          $interval.cancel(scope.stopTime);
          scope.stopTime = $interval(updateTime, scope.timer);
        }
      }
    }
}]);

Answer №2

It is important to assign a name to your function and reset its interval within the initialize method as shown below:

$scope.slider = {
    increment: 0,
    step: 1,
    positionTop: 0,
    initialize: function (step, isClicked) {
        if(isClicked) clearInterval($scope.interval);
        $scope.interval = setInterval(restartSlideInterval, 5000); // Resetting interval inside the function
        ...rest of the code...
};

// Define an independent function and avoid attaching it to $scope unnecessarily
function restartSlideInterval() {
    $scope.slider.step++;
    if($scope.slider.step === 5) $scope.slider.step = 1;
    $scope.slider.changeSlide($scope.slider.step);
}

$timeout(function () {
    $scope.slider.changeSlide($scope.slider.step);
    $scope.interval = setInterval(restartSlideInterval, 5000);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigate to the bottom of a Vue modal window by scrolling down

I am facing an issue with implementing a Vue calendar inside a modal. When the calendar appears, I want the window to automatically scroll to the bottom, but I am having trouble making it work. Unfortunately, I can't provide the code for the whole mod ...

Signs that indicate Angular has completed deferring

I'm having trouble grasping Angular's deferring and promises. I want to hide a "loading" message once all promises have been completed. Here's an example of my code: $scope.buildTeam = function () { $scope.Message = "loading..."; v ...

JavaScript can be used to open several tabs simultaneously within a single browser window

Looking to open multiple tabs in the main browser? Check out this code snippet: function openSM() { window.open("http://www.google.com","_blank"); window.open("http://www.yahoo.com","_blank"); window.open("http://www.bing.c ...

Tips for Removing AngularJS File from Source Code

Every time I launch my project, it displays all of my angular.JS files in the Source Code. Is there a way to exclude the js files from being shown? ...

Steps for modifying the CSS class of an <a> tag with Jquery/Javascript

I am attempting to dynamically change the class of a tab on the dashboard based on the selected page. In the dashboard, there are 3 tabs: <div> <ul class="menu"> <li class="MenuDashboard"><a href="#" >Dashboard</a&g ...

Escaping an equal sign in JavaScript when using PHP

I am currently working on the following code snippet: print "<TR><TD>".$data->pass_name."</TD><TD><span id='credit'>".$data->credit_left."</span></TD><TD><input type='button' val ...

transfer the output from the second selection to the adjacent div

I am utilizing a library called select2 specifically for single choice scenarios. My goal is to transfer the selected option to a different div once it has been chosen. Here is the code I have so far: https://jsfiddle.net/hxe7wr65/ Is there a way to ach ...

Searching with Neo4j, Java and the Angular library for accurate

When my web application is opened, it displays a form where users can input a list of comma-separated usernames. The application then queries the neo4j database to fetch information for each username. I am interested in implementing autocomplete functiona ...

Issue encountered with Axios PUT and GET requests - performance inconsistent

When using Axios to fetch data from a server and attempting a PUT request while needing data info from 3 tables to fill the form, sometimes it works and sometimes it doesn't. However, when debugging in the browser terminal, the PUT request always work ...

What is the best way to limit the character display to a maximum of 30 in Vue.js?

My current goal involves achieving the following task. In a certain variable, I currently have this text: let text = 'hey this is a super long phrase' I am looking to utilize a label to showcase the text, but with only a limited number of char ...

Is it possible to create a mouse-following effect with lighting using Javascript

Recently, I've been honing my Javascript skills and decided to create a follow-mouse function. After successfully implementing it, I started brainstorming a new concept that I'm unsure is achievable. Is there a way to develop an "orb of vision" ...

"Troubleshooting: Issues with jQuery Counter Functionality

Hey there, I'm new to JavaScript and jQuery! I've got this form set up with Bootstrap's disabled class: Note: the 'disabled' class in bootstrap properly disables and enables the button based on conditions. <form action="" met ...

What is the proper way to update text within a div using angularJS?

AngularJS Code: myEl = angular.element(document.querySelector('#divData')); myEl.html('This is text. <b>This is a bold text</b>'); By using the above method, you can change the content of the #divData element and add HTML ...

Express/axios fails to properly configure cookies and headers for response delivery

I am facing a complex issue with my project that involves two APIs. One API serves as the front-end of the application, while the other is for the back-end. The process simply entails sending requests from the front-end API to the back-end API. The front- ...

During the initial render in next-auth, the useSuspenseQuery function is triggered to fetch data without a defined token, resulting in an

Recently, I've started implementing the new useSuspenseQuery feature from react-query and I couldn't help but notice that the enabled property is missing on this hook. This has caused an issue with my useGetApiToken function, as it initially retu ...

Setting minimum and maximum limits for a JavaScript variable: tips and tricks

Currently, I am implementing a pagination feature using vuejs to display my algolia data. I am determining whether the user has clicked on either the previous button, next button, or directly inputted a page number (1, 2, 3, etc.) setPage: function(p ...

I am having trouble retrieving the properties of "2d" objects using tiles[i-1], unlike standard objects in JavaScript

I've been working on constructing a random map generator by utilizing a grid composed of tiles within a canvas. In my process, I'm investigating the properties of each tile tiles[i] before handling tiles[i-1]. While this procedure seems to functi ...

Retrieving and setting data in ReactJS

Currently utilizing Reactjs in tandem with MongoDB. Once a user makes a selection in Reactjs, that value is then sent over to MongoDB. addTodo(event) { event.preventDefault(); var roomID = this.state.selectedRoomID; console.log(Ro ...

How to remove a loop-rendered component from the DOM in Vue

My website has an image upload form where users can select multiple images. Once the images are selected, they are previewed and users can provide meta info such as Category and Type for each image. This functionality is implemented in the upload.vue file ...

Accumulation of style from various directives in AngularJS on a single element

Currently, I am working on developing a component framework and find myself in need of a method to apply styles from multiple directives to an element in a way that they can accumulate. The priority of the styles should be determined by the directive creat ...