0

I have a function in Javascript which is called by clicking a button and it takes approximately one minute to be finished. How can I disable the button after one click and enable it again after function is finished? I need this process to prevent spamming.

I tried the following piece of code, but it is not working. It is still possible to click the button several times.

Javascript:

function myFunc()
{
    document.getElementById("Btn").disabled = true;
    \\do something for one minute
    document.getElementById("Btn").disabled = false;
}

html:

 <button type="button" id="Btn" onclick="myFunc()">Generate!</button>
3
  • 1
    I assume \\do something for one minute is some async task, hence *.disabled = false; could be placed in the callback. Commented Apr 17, 2019 at 10:18
  • do something for one minute <- Maybe you are doing async process? Commented Apr 17, 2019 at 10:18
  • check here stackoverflow.com/questions/20281546/… Commented Apr 17, 2019 at 10:18

1 Answer 1

1

Your code is working fine. Maybe your function runs quickly that's why it appears as you can spam.

If you're calling function thru ajax, make sure async is false (default is true)

function myFunc() {
  document.getElementById("Btn").disabled = true;
  setTimeout(function() {
    console.log('hey');
    document.getElementById("Btn").disabled = false;
  }, 1000);

}
<button type="button" id="Btn" onclick="myFunc()">Generate!</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.