1

I want to enable button after certain time frame and again if I click on this button it should disable for this time frame .How to achieve this...

var timer2 = "00:30";
var interval = setInterval(function() {
  var timer = timer2.split(':');
  //by parsing integer, I avoid all extra string processing
  var minutes = parseInt(timer[0], 10);
  var seconds = parseInt(timer[1], 10);
  --seconds;
  minutes = (seconds < 0) ? --minutes : minutes;
  if (minutes < 0) clearInterval(interval);
  seconds = (seconds < 0) ? 59 : seconds;
  //minutes = (minutes < 10) ?  minutes : minutes;
  $('.countdown').html(minutes + ':' + seconds);
  timer2 = minutes + ':' + seconds;
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="countdown"></div>
<button type="button" id="demo">click</button>
johannchopin
  • 13,720
  • 10
  • 55
  • 101

1 Answers1

0

You can just wrap your code in a function and call that function on event click and at the beginning of your code run, and inside the function I added a check for the time to clear the interval and reset the timer, and using .setAttribute() and removeAttribute() to disable/enable the button:

function enableButton() {
  var timer2 = "00:30";

  var interval = setInterval(function() {
    var timer = timer2.split(':');
    //by parsing integer, I avoid all extra string processing
    var minutes = parseInt(timer[0], 10);
    var seconds = parseInt(timer[1], 10);
    --seconds;
    minutes = (seconds < 0) ? --minutes : minutes;
    if (minutes < 0) clearInterval(interval);
    seconds = (seconds < 0) ? 59 : seconds;
    //minutes = (minutes < 10) ?  minutes : minutes;
    $('.countdown').html(minutes + ':' + seconds);
      timer2 = minutes + ':' + seconds;
    if( minutes === 0 && seconds === 0) {
      clearInterval(interval);
      document.getElementById('demo').removeAttribute('disabled');
    }
    else {  
      document.getElementById('demo').setAttribute('disabled', true);
    }

  }, 100);
}

document.getElementById('demo').addEventListener('click', function() {
  enableButton();
});

enableButton();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="countdown"></div>
<button type="button" id="demo" disabled>click</button>
ROOT
  • 11,363
  • 5
  • 30
  • 45