0

I am trying to make a jquery script that counts down from 20 seconds when you call a function and then reset when it finishes. Is there a way of doing this?

4

4 回答 4

0

It's considered bad practice to use setInterval, so it's best to use setTimeout like so:

var timer = 20 * 1000;

function loop() {
  if (timer > 0) {
    $('#countdown').html(timer / 1000);
    timer -= 1000;
    setTimeout( loop, 1000 );
  } else {
    timer = 20 * 1000;
    $('#countdown').html(timer / 1000);
  }
}

loop();
于 2013-08-18T14:09:44.887 回答
0
(function($){
    /// initialize the variables
    var interval,
        $domElementThatContainsTheCountdown = $('.countdown'),
        count = 20;
    function start() {
        /// if the timer is already running, do nothing
        if(interval) return;

        $domElementThatContainsTheCountdown.text(count);
        /// set an interval on 1000ms (= 1 second)
        setInterval(function() {

            $domElementThatContainsTheCountdown.text(count);
            count -= 1;

            /// if the countdown has finished
            if(count === 0) {
                /// reset count
                count = 20;
                $domElementThatContainsTheCountdown.text(count);
                /// clear the interval
                clearInterval(interval);
            }
        }, 1000);
    }
}(jQuery));
于 2013-08-18T14:11:35.770 回答
0

Try this

var total = 20
var counter = 20
var timer = setInterval(function() { 
   $('#Msg').text(counter--);
   if (counter == -1) {
      //clearInterval(timer);
       $('#Msg').text(total);
       counter=20;
   } 
}, 1000);

This should work for below html
<span id="Msg">20</span>
于 2013-08-18T14:11:45.750 回答
0

try following

var timeVar = '', max = 20, starter = 0;

$("#btnStart").on("click",function(){
 timer();
});

function set (){
    if( max != starter){                        
        $(".timer").text((max).toString());
        max--;

        if(max == 0){
            max = 20;
        }
    }            
}

function timer(){
    timeVar = setInterval(set,500);          
}

working fiddle here: http://jsfiddle.net/3KLtc/1/

i hope it helps.

于 2013-08-18T14:23:08.217 回答