Call javascript function only once

0

Assuming I have a button that when clicked calls a javascript function. I wish that if this button were clicked several times I would only call this function once. Can you do that?

COMPLEMENT My question was incomplete. In case I need to do this: my button makes an ajax call. If the user clicks the button, the call starts, if it clicks again, before the call has ended, cancels that first call and makes a new one, and so on.

    
asked by anonymous 07.12.2017 / 16:30

4 answers

6

You can create a function that is named only in the scope in which it is executed, and after executing the action of addEventListener , call removeEventListener to remove it.

So:

var button = document.querySelector('#button');

var i = 0;
    
button.addEventListener('click', function click(e) {
    i++;
    console.log("Essa função foi chamada %d vez", i);
    button.removeEventListener('click', click);
});
<button id="button">Clica aí</button>

In this way, unlike using a variable indicating whether the button was clicked or not, the listener of that event will be removed, which may be interesting for performance gain, since you do not need to have a listener since the same will no longer do anything.

Addendum:

If you're using jQuery, you can use the one method to simplify the work:

$('#button').one('click', function (e) {
    // Executa somente essa vez, não mais que isso
});

It would be cool to have a look at these questions:

07.12.2017 / 16:38
0

Place a flag, I made a small example:

<button onclick="myFunction()">Click me</button>

<script>
var clicado = false;
function myFunction() {
    if(!clicado){
        alert('ok');
        clicado = true;
    }
}
</script>

So when you click on the button it arrows the flag as "clicked" then when the next click is done it will not do the action.

    
07.12.2017 / 16:38
0

Create a Boolean flag.

var jaFoiClicado = false; // começa com false pra poder ser clicado pela primeira vez

function clicarBotao() {
  if (!jaFoiClicado) {
    console.log("primeira vez");
    // substitui aqui dentro pelo seu código
    jaFoiClicado = true;
  } else {
    console.log("não vai clicar de novo nao!");
    }
}

// to simulando que clicou no botão 2x chamando a função :
clicarBotao();
clicarBotao();
    
07.12.2017 / 16:38
0

After the first execution, the value of the check variable will always be true, so it is possible to limit the qtd of calls from its function () to only 1.

JS:

var check = false;
function suaFunção(){
    alert("");
}
function onclick(){

   if(check==false){
       suaFunção();
   }
   check = true;
}
onclick();
onclick();

It will only display the alert once.

    
07.12.2017 / 16:48