I'm looking for a way, if possible, to debounce a button once it has been pressed. I'm developing a watchface (Versa 3) with a central button that, when pressed, fades away for 5 seconds and then reappears. However during that fade away a user could still continually mash the button (if so inclined, or just impatient), which could cause a string of button animations to ensue.
Is there a way to debounce the button during this fade process? I appreciate any advice, thank you.
Answered! Go to the Best Answer.
Best AnswerJust an idea, but perhaps you could set pointer-events to „none“ once the button is pressed and back to „visible“ when it appears back.
Or set a boolean like „isBusy“ and only process any action on the button if isBusy === false.
Or even simpler only react on pressing the button if it’s opacity === 1 🤔
Just an idea, but perhaps you could set pointer-events to „none“ once the button is pressed and back to „visible“ when it appears back.
Or set a boolean like „isBusy“ and only process any action on the button if isBusy === false.
Or even simpler only react on pressing the button if it’s opacity === 1 🤔
The busy flag is generally the way to go here. You can also use this to control other interface elements so things aren't acting over each other.
From an app I've been working on:
let isControlEnabled = true;
// ...
let ele_btn_status = document.getElementById("button_status");
ele_btn_status.addEventListener("click", (evt) => {
if (!isControlEnabled) {
return;
}
isControlEnabled = false;
// button action ...
setTimeout(() => {
isControlEnabled = true;
}, 5000); //wait 5000 ms (5 sec)
}
You may want to use onanimationend instead of setTimeout per @Gondwana 's suggestion (I haven't used this), or make the timeout dynamic by grabbing the animation element's dur property and multiplying it by 1000 to convert to ms (so if you were to change that duration you wouldn't also need to change this code)
Best AnswerThanks for the suggestion. I was able to get the desired effect with the "opacity" flag!
Best AnswerI'll confess it being a bit unusual, but in the use-case you described I thought it to be the most simple solution 😅
Best AnswerI use sth like that:
var now = this.getTimestamp(); // current time in milliseconds
var elapsedTime = now - this.lastClickTime;
if (elapsedTime <= 1000){
return; // no click this time
}
this.lastClickTime = now;
// process a click now
Best Answer