Javascript jQuery 显示 setTimeout 计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11693171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:45:06 来源:igfitidea点击:
jQuery show setTimeout timer
提问by sophistry
I'm trying to build a simple countdown application. Is it possible to show the timer value on setTimeout, or would I have to use a for loop?
我正在尝试构建一个简单的倒计时应用程序。是否可以在 setTimeout 上显示计时器值,还是必须使用 for 循环?
Thanks!
谢谢!
回答by mgraph
with setTimeout
:
与setTimeout
:
var n = 100;
setTimeout(countDown,1000);
function countDown(){
n--;
if(n > 0){
setTimeout(countDown,1000);
}
console.log(n);
}
or using setInterval
:
或使用setInterval
:
var n = 100;
var tm = setInterval(countDown,1000);
function countDown(){
n--;
if(n == 0){
clearInterval(tm);
}
console.log(n);
}
回答by user1558223
<script>
var timer = setInterval("mytimer()",1000);
seconds = 0;
function mytimer()
{
document.getElementById("div_timer").innerHTML = seconds; // this is the same as $("div_timer").html(timer) in jquery.
seconds++;
}
</script>
<body>
<div id="div_timer"></div>
</body>