Javascript倒计时逻辑
我在逻辑上有点问题:Javascript倒计时逻辑,javascript,timer,logic,Javascript,Timer,Logic,我在逻辑上有点问题: var seccount=60; var seccounter=setInterval(sectimer, 1000); function sectimer() { seccount=seccount-1; if (seccount < 0) { seccount=59; return; } document.getElementById("sectimer").innerHTML=seccount+ " seconds!"; var sec
var seccount=60;
var seccounter=setInterval(sectimer, 1000);
function sectimer() {
seccount=seccount-1;
if (seccount < 0) {
seccount=59;
return;
}
document.getElementById("sectimer").innerHTML=seccount+ " seconds!";
var seccount=60;
var seccounter=setInterval(sectimer,1000);
函数sectimer(){
seccount=seccount-1;
如果(秒计数<0){
seccount=59;
返回;
}
document.getElementById(“sectimer”).innerHTML=seccount+“seconds!”;
当它降到0时,计时器保持在0 2秒,然后再次跳到58。我在函数中尝试了一些不同的方法,例如:
function sectimer() {
seccount=seccount-1;
if (seccount <= 0) {
seccount=59;
return;
}
函数sectimer(){
seccount=seccount-1;
如果(seccount返回错误。请尝试以下操作:
var seccount=60;
var seccounter=setInterval(sectimer, 1000);
function sectimer() {
seccount--;
if (seccount < 0) {
seccount=59;
}
document.getElementById("sectimer").innerHTML=seccount+ " seconds!";
}
var seccount=60;
var seccounter=setInterval(sectimer,1000);
函数sectimer(){
秒计数--;
如果(秒计数<0){
seccount=59;
}
document.getElementById(“sectimer”).innerHTML=seccount+“seconds!”;
}
返回
导致函数立即终止,因此,当它进入条件if(seccount<0)
(如果seccount
为-1
),将seccount
更新为59
,然后它永远不会到达下面的元素更新,而是在return
时终止。然后,下一次它在一秒钟后运行时,seccount
会下降到58
,这显然不低于零,并跳到元素更新行。这就是为什么您我觉得您损失了2秒,因为您跳过了一次元素更新:-)返回的内容放错了位置。请尝试以下操作:
var seccount=60;
var seccounter=setInterval(sectimer, 1000);
function sectimer() {
seccount--;
if (seccount < 0) {
seccount=59;
}
document.getElementById("sectimer").innerHTML=seccount+ " seconds!";
}
var seccount=60;
var seccounter=setInterval(sectimer,1000);
函数sectimer(){
秒计数--;
如果(秒计数<0){
seccount=59;
}
document.getElementById(“sectimer”).innerHTML=seccount+“seconds!”;
}
返回
导致函数立即终止,因此,当它进入条件if(seccount<0)
(如果seccount
为-1
),将seccount
更新为59
,然后它永远不会到达下面的元素更新,而是在return
时终止。然后,下一次它在一秒钟后运行时,seccount
会下降到58
,这显然不低于零,并跳到元素更新行。这就是为什么您我想你损失了2秒钟,因为你跳过了一次元素更新:-)嗯,我可以这样做:
函数倒计时(n,lim=n){
result.textContent=n+“秒”;
设置超时(从,1000,n开始倒计时?--n:lim-1,lim);
}
从(5)开始倒计时;
嗯,我可以这样做:
函数倒计时(n,lim=n){
result.textContent=n+“秒”;
设置超时(从,1000,n开始倒计时?--n:lim-1,lim);
}
从(5)开始倒计时;
return;使函数在ui更新之前退出,因此ui不会更新为显示59,并在下一个间隔内跳到58。谢谢!在您的评论和Slavik的回答之间,我得到了所需的一切:解决方案和解释。return;使函数在ui更新之前退出,因此ui不会更新为display 59,在下一个间歇跳到58。谢谢!在你的评论和Slavik的回答之间,我得到了我需要的一切:一个解决方案和一个解释。效果很好。为什么返回会导致这种情况?为什么不需要返回?非常感谢!编辑:@Kenji回答了上面的问题。谢谢你的信息!在回答中解释。效果很好。为什么返回会导致这种情况?为什么不需要返回?非常感谢!编辑:@Kenji回答了上面的问题。感谢提供的信息!在回答中解释。