Javascript run one click at a time

Asked

Viewed 327 times

3

I have a problem when I click the button it triggers the function the amount of times clicked. when I click 3x in a row it fires the same 3x function generating slowness. how do I solve, code:

 function callSearch(){
 $('#Search').one('click', function(e){
   doSearch()
   callSearch()
 })
}
<button id="Search">Search</button>

My intention is after Arch, I want to release the click to be able to perform a new search again, but that no more than q one doSearch at a time.

  • You can lock your button after clicking and release it only after the end of the function execution

  • Did not work, test: $('#Search'). one('click', Function(e){ $(this). disabled = true doSearch() callSearch() $(this). disabled = false })

  • you can set it as disabled when the first click occurs and only release after the search Response

  • @Alexsanderrogerio Didn’t work because ? What happened ?

  • follows in fiddle https://jsfiddle.net/AlexRoPe/z61unf7m/5/ when I click it executes multiple times the code, in the example of I click several times fast, and is not blocked at any time

2 answers

2

You can use the attribute disabled to check whether the button has been clicked or not inside the Handler of the event. Something like this:

$('#btn').on('click', function() {
  $(this).prop('disabled', true);
  
  console.log('Clicou!');
  
  setTimeout(() => {
    // Após realizar algumas ações, basta remover o atributo
    // `disabled`, para que ele possa ser clicado novamente.
    $(this).prop('disabled', false);
  }, 750);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="btn">Clique-me</button>

As you can notice above, the event click is not even triggered if the button is disabled.

1

Our colleague Luiz Felipe already presented a solution to the problem, but as we are here to share ideas so let’s go!

HTML 5 allows us to add new customizable attributes to any element on the page.

We can take advantage of this facility and add one or several new attributes to the button in order to have extra information always available.

Follow the Example

$('.bBtn').on('click', function() {
  if ($(this).attr('status') == 'ativo') {
    $(this).attr('status','inativo');
    console.log('Botão pode chamar a função necessária');
    setTimeout(function(){ $('.bBtn').attr('status','ativo'); }, 1000);
  } else {
    console.log('Botão não pode chamar a função necessária');
  }
});
.bBtn {
  border: 1px solid #019234;
  padding: 12px;
  border-radius: 5px;
  width: 150px;
  text-align: center;
  color: #019234;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='bBtn' status='ativo'>Faça Algo</div>

In this example I show a behavior very similar to Luiz’s answer, to show that it is possible to solve the problem in several ways!!

try to click several times on the button to follow his behavior

with the jquery function attr() it is possible to access and manipulate any attribute referring to the selected element, so we can change the way we want the new attribute status button.

In the above example, I decided to use a condition that checks whether the attribute is active or inactive, and that way I know which way to go. Pointing out that this attribute, and the way it is interpreted (active/inactive), is defined by the programmer, this means that we are free to create several behaviors in a single element.

You also do not need to control the attributes with time functions like me and Luiz used in the example. In some cases we cannot determine the time it takes for a function to be completed, for example, an asynchronous request may vary its execution time from client to client.

That said, it would be interesting to manipulate the element attribute whenever the function is being completed or in a callback. So we’ll make sure everything’s okay.

Obviously I didn’t answer all this to show the same behavior of Luiz’s answer (kkk)

This next example will show you how useful attribute manipulation can be

$('.bBtn').on('click', function() {
  if ($(this).attr('status') == 'ativo') {
    $(this).attr('status', 'inativo');

    var quantidade = $(this).attr('quantidade');
    quantidade++;

    if (quantidade == 1) {
      console.log('Botão foi clicado ' + quantidade + ' vez');
    } else if (quantidade == 4) {
      console.log('Botão foi clicado ' + quantidade + ' vezes');
      $(this).css('padding', '43px');
    } else if (quantidade == 6) {
      console.log('Botão foi clicado ' + quantidade + ' vezes');
      $(this).css('background-color', '#019234');
    } else if (quantidade == 10) {
      console.log('Contagem Resetada');
      $(this).css('background-color', '#fff');
      $(this).css('padding', '12px');
      quantidade = 0;
    } else {
      console.log('Botão foi clicado ' + quantidade + ' vezes');
    }

    $(this).attr('quantidade', quantidade);



    setTimeout(function() {
      $('.bBtn').attr('status', 'ativo');
    }, 1000);
  } else {
    console.log('Botão não pode chamar a função necessária');
  }
});
.bBtn {
  border: 1px solid #019234;
  padding: 12px;
  border-radius: 5px;
  width: 150px;
  text-align: center;
  color: #019234;
  cursor: pointer;
  transition: 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='bBtn' status='ativo' quantidade='0'>Faça Algo</div>

I added another attribute and used a very silly example of stylization to show that manipulating the elements in this way can give us a very nice freedom, and also allows us to be more dynamic in creating pages.

Remember that all attributes are visible to the client, so only store information in attributes that can be known by anyone.

Browser other questions tagged

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