简体   繁体   English

如何在事件仍在发生时防止按钮单击? Javascript

[英]How to prevent button click while event still happening? Javascript

I try to find an answer to my question on the web but I didn't come across anything similar.我试图在 web 上找到我的问题的答案,但我没有遇到任何类似的事情。

Is there any way in JavaScript to prevent the same event from triggering two times, while the first trigger doesn't finish all the job? JavaScript 中是否有任何方法可以防止同一事件触发两次,而第一次触发并未完成所有工作?

I have some kind of spinning wheel and I want to prevent the possibility of pressing the button until it turns a full circle, the time it takes to turn a full circle is 2s, but when the first spin is done I want the button to work over and over again in the same way.我有某种纺车,我想防止按下按钮直到它转一圈,转一圈所需的时间是 2 秒,但是当第一次旋转完成时,我希望按钮工作以同样的方式一遍又一遍。

Here is my JavaScript code for that event.这是该事件的 JavaScript 代码。

let num = 0

spin2.addEventListener('click', () => {
  num += 360
  linija.style.transform = `rotate(${num}deg)`
  linija.style.transition = "all 2s"
})

Use setTimeout to do something like that:使用 setTimeout 来做这样的事情:

button.addEventListener('click', () => {
  if (buttonDisabled === false) {
    // Logic
    num += 360
    linija.style.transform = `rotate(${num}deg)`
    linija.style.transition = "all 2s"
    // Disable button
    buttonDisabled = true;
    button.textContent = 'Disabled';
    setTimeout(function() {
      buttonDisabled = false;
      button.textContent = 'Click me';
    }, 5000);
  }
});

Also, you should look at this: how to disable button for period and repeat that again (javaScript) .此外,您应该看看这个: 如何禁用按钮并再次重复(javaScript)

If the click function take some time, you can disable the button on the function start and enable it at the end of the function .如果click function 需要一些时间,您可以disable function上的button启动并在function结束时enable它。

 const delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms)) const clickHandler = async(e) => { e.disabled = true; await delay(1000) e.disabled = false; }
 <button onclick="clickHandler(this)">Click</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM