我想创建一个jquery倒数计时器,我尝试了以下代码,但是它不起作用。我该怎么办?
演示: https://jsfiddle.net/tbosn210/
var interval = setInterval(function() {
var timer2 = $("5:01");
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;
seconds = (seconds < 10) ? '0' + seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>
最佳答案
将您的timer2声明移出setInterval函数,在执行结束时将新的时间值分配给timer2以继续。
工作片段:
var timer2 = "5:01";
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;
seconds = (seconds < 10) ? '0' + seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>