AlirezaMah
AlirezaMah

Reputation: 51

disabling a button while running a function

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>

Upvotes: 0

Views: 1642

Answers (1)

ACD
ACD

Reputation: 1431

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>

Upvotes: 1

Related Questions