Skip to content
Advertisement

Enable button when counter reaches zero

I have a button its disabled and i want to put a counter inside it, what i want to do is when the counter reaches zero it get enabled, how can i do that? in the code below the counter doesn’t appear inside the button and i don’t want the reset button i just want the button to be enabled when it reaches zero, here is what i have tried so far:

function Countdown()
{
    this.start_time = "00:30";
    this.target_id = "#timer";
    this.name = "timer";
    this.reset_btn = "#reset";
}

Countdown.prototype.init = function()
{
this.reset();
setInterval(this.name + '.tick()',1000)
}

Countdown.prototype.reset = function()
{
    $(this.reset_btn).hide();
    time = this.start_time.split(":");
    //this.minutes = parseInt(time[0]);
    this.seconds = parseInt(time[1]);
    this.update_target();
}

Countdown.prototype.tick = function()
{
    if(this.seconds > 0) //|| this.minutes > 0)
    {
        if(this.seconds == 0)
        {
           // this.minutes = this.minutes - 1;
            this.seconds = 59
        } else {
        this.seconds = this.seconds - 1;
        }
    }
    this.update_target()
}

Countdown.prototype.update_target = function()
{
    seconds = this.seconds;
    if (seconds == 0) $(this.reset_btn).show();
    else if(seconds < 10) seconds = "0" + seconds;
    $(this.target_id).val(this.seconds)
}

timer = new Countdown();
timer.init();

$(document).ready(function(){
    $("#reset").click(function(){
        //timer = new Countdown();  
        timer.reset();
    });
});
.hidden {
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="text" id="timer" disabled>Counter should be inside me, and enable me when it reaches 0</button>
         <button id="reset">Reset</button>

Advertisement

Answer

This is much simpler than what you’ve got. Just use window.setTimeout().

Keep in mind that tracking time to a high precision is not super reliable in a browser. You may want to look at moment.js or use performance.now() for an easier API to handle that.

// Get refreence to span and button
var spn = document.getElementById("count");
var btn = document.getElementById("btnCounter");

var count = 5;     // Set count
var timer = null;  // For referencing the timer

(function countDown(){
  // Display counter and start counting down
  spn.textContent = count;
  
  // Run the function again every second if the count is not zero
  if(count !== 0){
    timer = setTimeout(countDown, 1000);
    count--; // decrease the timer
  } else {
    // Enable the button
    btn.removeAttribute("disabled");
  }
}());
<button id="btnCounter" disabled>Time left: <span id="count"></span></button>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement