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

0

I have a problem in 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 to add the "sweep" class to elements of a page (in this case buttons) that are added in turn, one by one for 5 seconds and then removed. But there are two problems:

  • When I turn the page and go back to the home page, it adds again one by one but I interrupted "the middle" on the first visit, it's as if the setTimeout was in stand by and when I go back the page stays where it was. causes the class to be added to buttons not the way I want.
  • When the page changes (in the first case 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 to this delay. The only thing that differs is the number of buttons that is larger.

I've been trying to solve this for days, but to no avail. Any help pff?

    
asked by anonymous 27.07.2016 / 12:52

1 answer

0

Try to implement your logic using setInterval() , where it runs at a defined interval, and you can stop the function.

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