当计数器达到零时启用按钮

时间:2017-05-28 18:53:51

标签: javascript button counter

我有一个禁用的按钮,我想在其中放置一个计数器,我想要做的是当计数器达到零时启用它,我该怎么做?在下面的代码中,计数器没有出现在按钮内部,我不希望重置按钮我只想在按钮启用时达到零,这是我到目前为止所尝试的:

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;
}
<button type="text" id="timer" disabled>Counter should be inside me, and enable me when it reaches 0</button>
         <button id="reset">Reset</button>

1 个答案:

答案 0 :(得分:4)

这比你得到的要简单得多。只需使用 window.setTimeout()

请注意,在浏览器中,追踪高精度的时间并不是非常可靠。您可能需要查看 moment.js 或使用 performance.now() 来更轻松地处理该问题。

&#13;
&#13;
<button id="btnCounter" disabled>Time left: <span id="count"></span></button>
&#13;
char* getWord(char str[], int n )
&#13;
&#13;
&#13;