我试图让这个脚本计数到指定的数字并返回到指定的数字,如下所示:19200、38400、57600、76800、96000、76800、57600、38400、19200 — 重复。到目前为止,这就是我所拥有的,但我似乎无法按照上面的顺序倒计时,它再次从 19200 重新开始。
$(function() {
var seconds = 19200;
var timerId = setInterval(function() {
seconds = seconds + 19200;
$("#counter").text(seconds);
if (seconds > "76800") {
clearInterval(seconds);
seconds = seconds - "19200";
}
}, 500);
});
最佳答案
逻辑有点问题,条件
if (seconds > "76800") {
将始终尝试将秒数保持在 76800 以上。
相反,您可能需要一个标志来跟踪计数的方向。看看下面:
更新:
工作演示在
$(function () {
var increment = 19200;
var seconds = increment;
var countUp = true;
var timerId = setInterval(function () {
$("#counter").text(seconds);
if (countUp) {
seconds += increment;
} else {
seconds -= increment;
}
if (countUp && seconds > increment*4) {
countUp = false;
} else if (!countUp && seconds <= increment) {
countUp = true;
}
}, 500);
});
关于javascript - 在Javascript中按顺序向上和向下计数到指定的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22804762/