Calling javascript function only once

Asked

Viewed 7,774 times

1

Suppose I have a button that when clicked calls a javascript function. I would like that if this button were clicked several times it would only call this function once. There are ways to do this?

COMPLEMENT My question was incomplete. In case I need to do the following: my button makes an ajax call. If the user clicks the button to start the call, in case he clicks again, before the call is over, cancel that first call and make a new one, so on.

4 answers

6


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

Thus:

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>

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

Addendum:

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

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

It would be nice if you take a look at these questions:

0

Put 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 by clicking the button it arrow the flag as "clicked" then by performing the next click it will not do the action.

0

Creates 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();

  • this wrong it performs more than once the click

  • It calls the function more than 1x, yes! But it only shows "first time" once. The function code should be in the first if (replace the console.log("first time") )

0

After the first run, the value of the check variable will always be true, so it is possible to limit the number of calls from the 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 Alert 1 time.

Browser other questions tagged

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