Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push user clicks to array and then display array after set time in Javascript?

I'm trying to write a function in which the user has a set amount of time to click, say, five divs on a page. The ids of the divs that are clicked on then get pushed to an array. I'd like the user to have maybe a couple of seconds to click, and then an alert pops up giving the values of the divs they clicked. My code so far pushes the values to an array, but I'm failing to make either of two things happen. Firstly (not shown in the below code), I'd like to it stop and show an alert when the user gets to five clicks (or, five values pushed to the array). I've tried looping the function until the array length is equal to 5, but no dice.

Secondly, shown below, I'd like to give a few seconds for clicking, then the alert shows up with the userClicks array values. Again, no dice. What am I missing here? To be clear, I don't have to be able to do both things within the single function, but I'd like to try out both as an option, if possible. Here's my current code:

let userClicks = [];
function reply_click(clicked_id) {
    setTimeout(function () {
        userClicks.push(clicked_id);
    }, 3000);
    alert(userClicks);
}

Here's the related HTML:

<div id="game-container">
    <div id="0" class="cell" onClick="reply_click(this.id)"></div>
    <div id="1" class="cell" onClick="reply_click(this.id)"></div>
    <div id="2" class="cell" onClick="reply_click(this.id)"></div>
    <div id="3" class="cell" onClick="reply_click(this.id)"></div>
    <div id="4" class="cell" onClick="reply_click(this.id)"></div>
    <div id="5" class="cell" onClick="reply_click(this.id)"></div>
    <div id="6" class="cell" onClick="reply_click(this.id)"></div>
    <div id="7" class="cell" onClick="reply_click(this.id)"></div>
    <div id="8" class="cell" onClick="reply_click(this.id)"></div>
</div>

Thank you!

like image 709
Maccles Avatar asked Mar 25 '26 17:03

Maccles


1 Answers

First things first.

For the first requirement, i.e. showing the alert after 5 clicks, it's simple:

let userClicks = [];
function reply_click(clicked_id) {
  userClicks.push(clicked_id);
  if (userClicks.length === 5) {
    alert('5 clicks done!');
  }
}

For the second requirement, I'm not sure if I understood correctly, but if you meant that the user should make 5 clicks within 2 second's timeframe, that can also be done. Something like this:

let userClicks = [];
const startTime = new Date();
function reply_click(clicked_id) {
  const now = new Date();
  const seconds = (now.getTime() - startTime.getTime()) / 1000;
  if (seconds > 2) {
    alert('Sorry, you lost the game!');
    userClicks = [];
  }
}

Now, it's your job to combine the two.

like image 184
technophyle Avatar answered Mar 27 '26 07:03

technophyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!