pairof9s pairof9s - 5 months ago 10
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.

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

Answer

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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click-button">Generate Random Numbers</button>

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

Comments