function startTimer(duration, text, value) {
var timer = duration,
minute, second, value;
setInterval(function() {
minute = parseInt(duration/ 60, 10);
second = parseInt(duration% 60, 10);
if (minute < 10) {
minute = "0" + minute;
} else {
minute = minute;
}
if (second < 10) {
second = "0" + second;
} else {
second = second;
};
text.text(minute + ":" + second);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function() {
var duration = 1200,
text = $('#time'),
value = 10;
minute = parseInt(duration/ 60, 10);
second = parseInt(duration% 60, 10);
if (minute < 10) {
minute = "0" + minute;
} else {
minute = minute;
}
if (second < 10) {
second = "0" + second;
} else {
second = second;
};
$("#time").text(minute + ":" + second);
startTimer(duration, text, value);
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>Remain <span id="time"></span> minute</div>
&#13;
我想使用一个简单的倒数计时器。 Firsty我定义了一个持续时间,我发送持续时间类型的秒和分钟来跨越文本。我也定义了一个值。例如,值为20.我想减少每分钟的值。当值相等时,零功能将完成。我希望我能够解释得足够多。
答案 0 :(得分:1)
elapsed
来跟踪已经过了多少秒value
可被60整除时,扣除elapsed
,意味着一分钟过去了run
大于0 value
一次
function startTimer(duration, text, value) {
var timer = duration,
minute, second, value, elapsed = 0;
var run = function() {
minute = parseInt(timer / 60, 10);
second = parseInt(timer % 60, 10);
if (minute < 10) {
minute = "0" + minute;
} else {
minute = minute;
}
if (second < 10) {
second = "0" + second;
} else {
second = second;
};
text.text(minute + ":" + second);
if (--timer < 0) {
timer = duration;
}
elapsed++;
if (elapsed % 60 == 0) value--;
if (value <= 0) {
clearInterval(timerId);
}
$("#time").text(minute + ":" + second);
$('#val').text(value);
if (value > 0) {
setTimeout(run, 1000);
}
};
run();
}
window.onload = function() {
var duration = 1200,
text = $('#time'),
value = 10;
startTimer(duration, text, value);
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Remain <span id="time"></span> minute</div>
<div>Value <span id="val"></span>
</div>
&#13;