我正在尝试创建一个jquery脚本,当你调用一个函数时,该脚本从20秒开始倒计时,然后在完成时重置。有没有办法做到这一点?
答案 0 :(得分:0)
使用setInterval被认为是不好的做法,所以最好像这样使用setTimeout:
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();
答案 1 :(得分: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));
答案 2 :(得分:0)
试试这个
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>
答案 3 :(得分:0)
尝试以下
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);
}
在这里工作小提琴:http://jsfiddle.net/3KLtc/1/
我希望它有所帮助。