Stop a Function already started in Jquery

Asked

Viewed 540 times

1

The problem is this. I have a function called showJsonProducts(); I want that when I call another Function it stops running, example:

$('.btn').click(function(){
 showJsonProducts.stop(); 
ou 
 showJsonProducts().break();

there is such a thing?

1 answer

1


Once loaded into memory, there is no way to prevent the function from being called (at least I don’t know a method).

But you can create a global variable that ignores the content (or part of it) of the function. Set the variable to false and include the content of the function within a if verifying the status variable. When you call the other function, change the status from the variable to true:

var ativa = false;
function teste(){
   if(!ativa){
      // ... todo o conteúdo da função aqui
      alert("Olá!");
   }
}

function desativa(){
   ativa = true;
}
<input type="button" value="Chamar função" onclick="teste()" />
<input type="button" value="desativar função" onclick="desativa()" />

This way the function will still be called, but will have no effect because it will not enter the if within it. In your case:

$('.btn').click(function(){
    ativa = true;
});

Edit

Another way is to redefine the function:

window.teste = function(){
   return false;
}

Example:

function teste(){
   alert("Olá!");
}

function desativa(){
   window.teste = function(){
      return false;
   }
}
<input type="button" value="Chamar função" onclick="teste()" />
<input type="button" value="desativar função" onclick="desativa()" />

Browser other questions tagged

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