How do I check whether a button has been clicked in the last X seconds? | SoloLearn: Learn to code for FREE!


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.

5/30/2020 8:08:38 AM


6 Answers

New Answer


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?


Create a variable, buttonLastClickTime: let buttonLastClickTime =; Then, grab your button and register a click handler, that updates that variable: document.getElementById("mybutton").addEventListener("click", () => { buttonLastClickTime =; }); And now you can check, whenever you need to: timeSinceLastClick = - buttonLastClickTime; Now you have the answer, in milliseconds!


You can also use to keep track of elapsed time.


Here are the demo step by step: Step 1: Update the combo counter display Learning objective: Global variable. Step 2: Calculate time between last click and current time Learning objectives : - - 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. 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.


Ohh I didn't even think of using the date. Thanks, btw


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.