Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
Disable button until function is done

I am trying to disable the button until the code is successfully executed. Unfortunately, the button is activated too early, the function is still running. How can I prevent this?

$("#myButton").click(function() {
    $(this).prop("disabled", true)
    doSomethingFunction()
    $(this).prop("disabled", false)
});

Edit: Thank you all for your help. I have adjusted my code. Can you do it this way or are there better ways?

class TestClass
{
    static doSomethingFunction() {
        return new Promise(function (resolve, reject) {
            setTimeout(function () { console.log("function is done");  resolve(self);  }, 5000);
        })
    }
}

$("#myButton").click(function() {
    $(this).prop("disabled", true)
    TestClass.doSomethingFunction().then(r => $(this).prop("disabled", false))
});

The second solution does not work for me, because "completely done" is output before "function is done"

class TestClass
{
    static doSomethingFunction(callback) {
        setTimeout(function () { console.log("function is done");}, 2000);

        if(callback !== undefined){
            callback();
        }
    }
}

$("#myButton").click(function() {
    $(this).prop("disabled", true)

    TestClass.doSomethingFunction(function(){
        console.log("completely done")
    });
});

What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Consider the following.

var myData;

function doSomethingFunction(callback){
  $.get("someplace.php", function(data){
    myData = data;
    if(callback !== undefined){
      callback();
    }
  });
}

$("#myButton").click(function() {
  var $self = $(this);
  $self.prop("disabled", true);
  doSomethingFunction(function(){
    console.log(myData);
    $self.prop("disabled", false);
  });
});

This allows you to pass in code to run once the function is complete. In this example, maybe it's getting data from the server. This may take almost no time, or maybe the report takes 1.2 seconds to generate. Either way it will not be run until the AJAX is successful.

Update

Here is an example, based on the following: How do I use jQuery promise/deffered in a custom function?

$(function() {
  function doSomething() {
    var deferred = new $.Deferred();
    setTimeout(function() {
      deferred.resolve(10);
    }, 10 * 1000);
    return deferred;
  }

  $("button").click(function() {
    var $self = $(this);
    console.log("Disabled");
    $self.prop("disabled", true);
    doSomething().then(function() {
      $self.prop("disabled", false);
      console.log("Enabled");
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Start</button>

This will run for 10 seconds and then enable the button. Applying it to your example.

class TestClass {
  static doSomethingFunction() {
    var deferred = new $.Deferred();
    setTimeout(function() {
      deferred.resolve(10);
    }, 5 * 1000);
    return deferred;      
  }
}

$("#myButton").click(function() {
  var $self = $(this);
  $self.prop("disabled", true);
  TestClass.doSomethingFunction().then(r => $self.prop("disabled", false));
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda