pairof9s
pairof9s

Reputation: 17

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);
     });
 });

Upvotes: 0

Views: 1580

Answers (2)

omarjmh
omarjmh

Reputation: 13896

How about we set a variable that increments by one every second using setInterval, and only allow the click to function if that variable is under 10:

In this example, you get a different alert after 10 seconds.

   var time = 0;

function start() {
  setInterval(function() {
    var curr = $('#container').text();
    time++;
    $('#container').text(time);
  }, 1000);
}

$('#btn').on('click', function(e) {
  if ($('#container').text() < 11) {
     console.log('K cool, enough time left');
  } else {
     alert('TOO Late');
  }
})

start()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  0
</div>
<button id='btn'>Click me Before 10 seconds</button>

Upvotes: 0

Richard Hamilton
Richard Hamilton

Reputation: 26444

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>

Upvotes: 2

Related Questions