+ 1
How do I check whether a button has been clicked in the last X seconds?
I am creating a combo mechanic for a game I have been working on and can't figure out how to check when something was clicked. https://code.sololearn.com/WNp8epNaSTC7/?ref=app
6 Answers
+ 4
What you want to achieve should be divided into two parts:
1. Increment combo count at each click on the button
2. a. Decrement combo at each second, min 0.
or
2. b. Check each second, if no more click, then execute combo action.
Which one is your thoughts? 2a or 2b?
+ 4
Create a variable, buttonLastClickTime:
let buttonLastClickTime = Date.now();
Then, grab your button and register a click handler, that updates that variable:
document.getElementById("mybutton").addEventListener("click", () => {
buttonLastClickTime = Date.now();
});
And now you can check, whenever you need to:
timeSinceLastClick = Date.now() - buttonLastClickTime;
Now you have the answer, in milliseconds!
+ 4
You can also use
window.performance.now()
to keep track of elapsed time.
https://code.sololearn.com/W07Ikn0cn2TS/?ref=app
+ 4
Here are the demo step by step:
Step 1: Update the combo counter display
https://code.sololearn.com/WYWhDIFGdGAf/?ref=app
Learning objective: Global variable.
Step 2: Calculate time between last click and current time
https://code.sololearn.com/WVwjcqVv1VaO/?ref=app
Learning objectives :
- performance.now()
- setTimeout
Step 3: When last click is longer than a specific time (I use 3 seconds for clearer demo purpose only), combo action is triggered.
https://code.sololearn.com/WhR1w1K3Cz70/?ref=app
Learning objectives :
- If statement
- set up to implement reset feature
- functional programming (using utility in step 1)
This will be an interesting topic to film a YouTube video tutorial, I might film a step-by-step one today or tomorrow testing my new microphone.
+ 1
Ohh I didn't even think of using the date. Thanks, btw
0
I think 2b will work the best in this case, how would I achieve this? I have figured out everything but how to check when the button was clicked. Thanks for answering, much appreciated.