Strange behaviors when using setinterval with classes

Currently working on enhancing a slider functionality, and I have observed that everything is functioning smoothly -

function Slider(element) {

    this.i = 0;

    this.element = element;

    var self = this;

    this.timer = window.setInterval(function() {
        switch (self.i) {
            case 0:
                $(element).velocity({ translateX: "-33.3333%" });
                self.i++;
            break;
            case 1:
                $(element).velocity({ translateX: "-66.6666%" });
                self.i++;
            break;
            case 2:
                $(element).velocity({ translateX: "0%" });
                self.i = 0;
            break;
        }
    }, 2000);
}

Slider.prototype.stop = function() {
    window.clearInterval(this.timer);
}

var i = 0;
$(".multi").each( function(){
    label = "label_" + i;
    window[label] = new Slider($(this));
    console.log(window[label]);
    console.log(label);
    console.log(i)
    i++;
});

$(".multi-nav a").click( function(e){
    e.preventDefault();
    number = $(this).parent().attr("class").split(" ").pop();
    label = "label_" + number;
    console.log(label)
    console.log(window[label]);
    window[label].stop();
});

Check out the demo here - http://codepen.io/JordanDWhalen/pen/QjGNYm

However, I am currently working on adding animations to toggle classes on the targets of the events that stop the interval:

function Slider(element) {

    this.i = 0;

    this.element = element;

    var self = this;

    this.timer = window.setInterval(function() {
        switch (self.i) {
            case 0:
                $(element).velocity({ translateX: "-33.3333%" });
                $(".multi-nav a").velocity({ opacity: ".5" });
                $(".multi-nav ." + self.i).velocity({ opacity: "1" });
                self.i++;
            break;
            case 1:
                $(element).velocity({ translateX: "-66.6666%" });
                $(".multi-nav a").velocity({ opacity: ".5" });
                $(".multi-nav ." + self.i).velocity({ opacity: "1" });
                self.i++;
            break;
            case 2:
                $(element).velocity({ translateX: "0%" });
                $(".multi-nav a").velocity({ opacity: ".5" });
                $(".multi-nav ." + self.i).velocity({ opacity: "1" });
                self.i = 0;
            break;
        }
    }, 2000);
}

Slider.prototype.stop = function() {
    window.clearInterval(this.timer);
}

var i = 0;
$(".multi").each( function(){
    label = "label_" + i;
    window[label] = new Slider($(this));
    console.log(window[label]);
    console.log(label);
    console.log(i)
    i++;
});

$(".multi-nav a").click( function(e){
    e.preventDefault();
    number = $(this).parent().attr("class").split(" ").pop();
    label = "label_" + number;
    console.log(label)
    console.log(window[label]);
    window[label].stop();
});

See the updated demo here - http://codepen.io/JordanDWhalen/pen/RWoaYR

Answer №1

Seems like the problem stemmed from the animations triggering on multiple matching elements simultaneously. This caused both intervals to be halted in order for either one to cease animating.

var sliderId = 0;
function Slider(element) {

    this.id = sliderId;
    sliderId++;

    this.i = 0;

    this.element = element;

    var self = this;

    this.timer = window.setInterval(function() {
        switch (self.i) {
            case 0:
                $(element).velocity({ translateX: "-33.3333%" },{delay: 1500, duration: 500 });
                $(".multi-nav." + self.id + " .active" ).removeClass("active");
                $(".multi-nav." + self.id + " ." + self.i).addClass("active");
                self.i++;
            break;
            case 1:
                $(element).velocity({ translateX: "-66.6666%" }, { delay: 1500, duration: 500 });
                $(".multi-nav." + self.id + " .active" ).removeClass("active");
                $(".multi-nav." + self.id + " ." + self.i ).addClass("active");
                self.i++;
            break;
            case 2:
                $(element).velocity({ translateX: "0%" }, {delay: 1500, duration: 500 });
                $(".multi-nav." + self.id + " .active" ).removeClass("active");
                $(".multi-nav." + self.id + " ." + self.i ).addClass("active");
                self.i = 0;
            break;
        }
    }, 2000);
}

By including the .id in the object and using it within my animations, I was able to resolve the issue!

Answer №2

When implementing the following steps:

  • call Slider() on the ".multi-wrap" wrappers, instead of the ".multi" elements
  • locate the ".multi" and ".multi-nav" elements within each wrapper
  • incorporate the stop functionality in the Slider() function rather than using a .stop() method

You will notice that :

  • the necessity for this.xxx, properties diminishes in favor of private variables
  • the reliance on globals diminishes
  • the requirement for new lessens and invocation becomes simpler.

Your implementation may resemble something like this :

function Slider(index, wrapper) {
    var i = 0;
    var $multi = $(wrapper).find(".multi");
    var $multiNav = $multi.siblings(".multi-nav");
    var timer = window.setInterval(function() {
        $multi.velocity({ translateX: ['-33.3333%', '-66.6666%', '0%'][i] });
        $multiNav.velocity({ opacity: '1' });
        $multiNav.find("a").velocity({ opacity: '.5' });
        i = (i + 1) % 3;
    }, 2000);
    $multiNav.find("a").click(function(e) {
        e.preventDefault();
        window.clearInterval(timer);
    });
}
$(".multi-wrap").each(Slider);

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

Unable to retrieve information using the post method in Express framework

After creating a basic code to fetch data from the client, I am facing an issue where req.body.firstname is showing as undefined. Here is the code snippet: const express = require('express'); const app = express(); const body ...

What is the best way to show only the weekdays on the x-axis?

My goal is to create a scatter-linked graph using D3.js, showcasing the people count for various shifts on different dates in January 2020. Here is the code snippet I am working with: <!DOCTYPE html> <html lang="en" > <head> & ...

What causes inability for JavaScript to access a property?

My current coding project involves the usage of typescript decorators in the following way: function logParameter(target: any, key : string, index : number) { var metadataKey = `__log_${key}_parameters`; console.log(target); console.log(metadataKey ...

Issue with Jquery: Checkbox fails to get checked in Internet Explorer 7

Having trouble with checking a checkbox, I've attempted the following steps: $('#someId').attr('checked','checked'); $('#someId').attr('checked', true); Both of these methods are effective for I ...

Creating numerous duplicates of a highly nested immutable Object can be done by using a combination of spread operators

I am currently working on retrieving data from firebase/firestore using Javascript. I have created a function where I retrieve my products collection and pass this data to the React state.products by utilizing the setState() method. My objective is to tra ...

The Ajax data was not displayed in the console log, instead an error message was returned stating "http://localhost/IFICSV3/public/sla/sla/getbranch/180 not found"

I am attempting to make a dropdown option dependent on another using ajax. I want to view the data in the console to see if it is successful or not. I expect the data to be displayed in the console log, but instead, an error is being given. http://local ...

What is the best way to access data from outside a forEach loop in JavaScript?

I am trying to access the value of my uid outside of the foreach loop in my code. Can anyone assist me with this? This is the code I am working with: var conf_url = "https://192.168.236.33/confbridge_participants/conference_participants.json?cid=009000 ...

Unable to display JSON results in a tabular format

After successfully implementing the AJAX method in jQuery, I am able to receive a response. However, I am encountering difficulties when trying to display the arrays in a table format. success:function(resp){ var json =JSON.parse(JSON.stringif ...

Attempting to align navigation bar in the middle of the page

I'm facing some issues with centering the navigation bar on my website. I attempted to use a wrapper div to center it, but unfortunately, it didn't work out as expected. The only thing that seems to be working within that div is adjusting the lef ...

Unsynchronized Request Sequencing

Seeking advice on enhancing a previously accepted answer related to chained ajax requests can lead to some interesting solutions. One proposed solution involves sequencing 3 ajax requests in an asynchronous chain: var step_3 = function() { c.finish() ...

no visible text displayed within an input-label field

Currently, I have started working on a multi-step form that is designed to be very simple and clean. However, I am facing an issue where nothing is being displayed when I click on the next arrow. I am puzzled as to why it's not even displaying the te ...

Position the SVG next to the link text in a Bootstrap navbar brand

I am using the .navbar-brand class from Bootstrap to include an SVG in my navbar. However, I want to display text next to the SVG and align it properly. The SVG and text are currently in the navbar but they are not aligned correctly. Below is the code snip ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

Unable to apply styling to body element in style.css file when using Node.js

I recently launched a basic Node.js website but encountered an unusual issue. When trying to style the body using the default style.css stylesheet provided by Express, I found that it was not recognizing it. The only workaround was to add the class body di ...

Avoiding code execution by injections in Javascript/Jquery

Currently, I'm fetching JSON data for a .getJSON function in Jquery. To ensure the data's security, I am considering using .text (I believe this is the correct approach). The JSON has been successfully validated. Below is the script that I am cu ...

Locate a specific item in an array using AngularJs based on a key and present its value on the View

Imagine you have an array of objects: $scope.objArr = [{key:1,value:'value1'},{key:2,value:'value2'},{key:3,value:'value3'}]; And a variable that corresponds to key. For instance: $scope.a = 3; In the Controller, you want ...

Solving the jQuery Enigma: Why the If Statement Fails to Execute

I am struggling with implementing an if-loop inside my success function for AJAX in my project. The success function retrieves the response text from a python script, which can be either "SUCCESS" or "EMPTY". Although I receive the correct data and my aler ...

Saving and accessing AJAX XML responses in sessionStorage

I have encountered an issue with storing XML response from ajax into sessionStorage. Despite successfully setting the data, I am unable to retrieve it. $.ajax({ url: '/webservice.svc/getProfile', data: { "memberId": $(authenticat ...

Is there a way to keep the input field data in my form in next js persist even after the page refreshes?

I am currently developing a form in Next.js and I need the data to persist even after the page is refreshed or reloaded. Unfortunately, local storage does not work with Next.js, so I am exploring other alternatives. Every time I try to use local storage, ...

Setting up an i18n project in AngularJS

I just embarked on my angularjs journey yesterday with little to no prior knowledge about it. My initial goal is to centralize all the labels for my UI in a file (to facilitate swapping them out for i18n). As far as I know, this can be achieved by importi ...