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!