Problem with functions being executed multiple times

4

I'd like to know how to fix this problem. Example:

I have a fadeIn / fadeOut function. The event that triggers the function is the onclick on some element. The question is: How do I prevent when I double clicks or more, the function runs every time I click, one instance over the other?

In this way, the function executes again and buga the entire effect. I would like to know how to "stop" the office of the function that is already running, and only then run it again, upon noticing a new click before it is completed ...

It has something to do with that "function (e) {e.preventDefault ();}"?

I do not know if I explained it well, but whoever understands and can help I'm very grateful. See you.

    
asked by anonymous 13.10.2016 / 13:09

4 answers

5

With a code you could respond better, but basically what you need to do is have a global variable that controls whether it has already been executed or not, something like this:

var fadeJaExecutado = false;

in the function that will perform the effect:

if (!fadeJaExecutado) {
    //faz o que tem que fazer
    fadeJaExecutado = true;
}

Now if what you want is that it does not run more than once simultaneously the solution is another one, it would look something like this:

var fadeExecuting = false;

function fade() {
    if (!fadeExecutando) {
        fadeIn();
        fadeExecutando = true;
    } else {
        fadeOut();
        fadeExecutando = false;
    }
}

It may be that part of the logic of fadeIn() / fadeOut() might be better to bring pro fade() , like setTimeout() . But it would be better to see the code you are doing first. I'll improve if the question gets better.

    
13.10.2016 / 13:28
2

You can add a class to the element in the click, and check if this class exists

 $('#test-btn').on('click', function(){
        if(!$('#test').hasClass('fadding')){
        $('#test').addClass('fadding').fadeToggle('fast', function(){
        $(this).removeClass('fadding');
      });
    }
  });

I created a jsFiddle with the example

    
13.10.2016 / 14:08
0

ev.preventDefault() will prevent the default behavior of the element, eg; ev.preventDefault() in a click event of a <a> will prevent the href='' link from being called.

If you are using jQuery, you can use the :animated property to check if the element is being animated, eg:

if (!$('.my-element').is(':animated')) { $('.my-element').fadeToggle(); }

From what I understood of your problem, it would be something like this:

$('.my-button').click(function (ev) {
  ev.preventDefault(); // ignore the href='#'

  var $fadeElement = $('.my-fade-element');

  if (!$fadeElement.is(':animated')) {
      $fadeElement.fadeToggle();
  }
});
13.10.2016 / 14:25
-1

My friend, check out the Throttle and Debounce standards, I believe the article below will help.

Throttle and Debounce

    
13.10.2016 / 14:21