使用jquery每5秒倒计时一次



我想从下拉列表中选择秒,这一秒将显示倒计时,如选择5秒,5秒倒计时,直到A按钮变绿。5秒后,B将变绿,直到D变绿。

我有这个倒计时代码。

var Remaining = $('#Second').val();
var downloadTimer = setInterval(function() {
document.getElementById("lbltime").textContent = Remaining;
Remaining = Remaining - 1;
if (Remaining <= 0)
clearInterval(downloadTimer);
}, 1000);

,但它只在一个倒计时中停止,而不是重复。

图像

您可以使用setInterval API。

setInterval(function(){
/* Write your code here that runs for every 5 seconds*/
},5000)

在这里了解setInterval api

我希望你想要下面这样的东西。

var Remaining = $('#Second').val();
var downloadTimer;
function start(select) {
clearInterval(downloadTimer);
$('#Second').val($(select).val());
Remaining = $('#Second').val();
document.getElementById("lbltime").textContent = Remaining;
$('.dv.active').removeClass('active');
if ($(select).val() == 0)
return;
$('.dv:first').addClass('active');
downloadTimer = setInterval(function() {
Remaining = Remaining - 1;
if (Remaining <= 0) {
Remaining = $('#Second').val();
var current = $('.dv.active').removeClass('active');
if (current.next('.dv').length)
current.next('.dv').addClass('active');
else {
$('.dv:first').addClass('active');
// If you want to stop after first iteration then uncomment below line.
// clearInterval(downloadTimer);
}
}
document.getElementById("lbltime").textContent = Remaining;
}, 1000);
}
.dv {
height: 50px;
width: 50px;
display: inline-block;
background-color: #ddd;
}
.dv.active {
background-color: #0F0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="Second" val="0" />
<select onchange="start(this)">
<option value="0"> select</option>
<option value="3"> 3</option>
<option value="4"> 4</option>
<option value="5"> 5</option>
</select>
<div>Time Remaining: <label id="lbltime"></label></div>
<div>
<div class="dv" id="a"> A</div>
<div class="dv" id="b"> B</div>
<div class="dv" id="c"> C</div>
<div class="dv" id="d"> D</div>
</div>

最新更新