Add class to multiple elements, one at a time in Jquery

Asked

Viewed 475 times

0

I have a problem with the following code:

        $("button").each(function(index){       
            // add the class
            setTimeout(function(){
                $(this).addClass("varrimento");
            }.bind(this),index*5000);
            // remove the class
            setTimeout(function(){
                $(this).removeClass("varrimento");
            }.bind(this),(index+1)*5000); 
        });

This code is used to add the "scan" class to the elements of a page (in this case they are buttons) where it is added one by one for 5 seconds and then removed. Only there are two problems:

  • when I change page and go back to the home page, add again one by one but as I interrupted "in the middle" on the first visit, it is as if the setTimeout is in stand by and when I return the page continues where it was, what makes the class being added to buttons not the way I want.
  • When changing page (the first time the page load is done, the class starts to be added to the buttons), the next page takes +/- 15 seconds to start adding the class, with no apparent reason for this delay. The only thing that differs is the number of buttons that is larger.

I have been trying to solve this for several days, but without success. Some help pff?

  • The browser suspends when you change pages, maybe that’s why the setTimeout also stops... Can you explain better "the following page takes +/- 15 seconds to start adding"? I see no reason for that in this code

  • Well, that’s the point, I don’t see the point. What the class is doing is flash the buttons, appear and disappear for 5 seconds. right on the first page starts to happen soon, when switching to the second, which has 3 more buttons takes that time to start putting the class on buttons

  • You can reproduce this problem in a jsFiddle?

  • I’ll try and get it in here. but on the question you said about setTimeout, I’m not using a browser but a mobile app with phonegap

  • @Tiagopina Solved your problem?

1 answer

0

Try to implement your logic using setInterval(), where it is executed in a defined interval, and can be stopped performing the function.

    var timerId = setInterval(function () {
        //Faz alguma coisa aqui!
        if(condicao == true){
            //Termina a execução
            clearInterval(timerId);
        }
    },5000);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.