pairof9s pairof9s -5 years ago 195
jQuery Question

Timer for button clicks

We are preparing a "game" button with class function that you click as often as possible to generate (at this time) an increasing random number. However, we want it to stop functioning after a set time period, 10 seconds.

The click code below is for the number generation, but not sure how to create the timer to stop the button, and for testing purposes, display an alert.

{$('.score').html(function(i, val)
{return val - Math.floor(Math.random()* -11);});

Answer Source

I will admit that this is a bit of a hack and could have better performance, but for this example it will work.

Create a times array which will store the time that a click event was recorded. The getTime() method returns the number of milliseconds since the 1970 epoch. To get the number of seconds, we simply multiply this by 1000.

Every click, we will check whether 10 seconds have passed since the first click was recorded.

Check out the snippet

var clickTimes = [];                         // Store click times here

/* Get number of ms since the epoch with getTime and add to array. On every click check whether the time has elapsed */

$('.click-button').click(function() {
  clickTimes.push(new Date().getTime());
    if (new Date().getTime() - clickTimes[0] < 10000) {
        $('.score').html(function(i, val) {
            return val - Math.floor(Math.random() * -11);
    else {
        $(".score").html("Time's up! Click again to try again!");
        clickTimes.length = 0;             // Clear array
<script src=""></script>
<button class="click-button">Generate Random Numbers</button>

<p class="score"></p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download