Javascript 如何在javascript中设置一分钟计数器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6893130/
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
How to set one minute counter in javascript?
提问by Karthick Terror
In my project ,I have list of questions, for every question have three option answers.
在我的项目中,我有问题列表,每个问题都有三个选项答案。
After see the question if i want answer that question means click "show answer" button . when I click button ,counter starts for one minute after one minute error will show .
看到问题后,如果我想回答该问题,则表示单击“显示答案”按钮。当我单击按钮时,计数器会在一分钟后开始一分钟,错误将显示。
can any one help ?
有人可以帮忙吗?
回答by redShadow
You could use something like this:
你可以使用这样的东西:
function gameLost() {
alert("You lose!");
}
setTimeout(gameLost, 60000);
UPDATE:pass function reference to setTimeout()
instead of code string (did I really write it that way? O_o)
更新:将函数引用传递给setTimeout()
而不是代码字符串(我真的那样写吗?O_o)
EDIT
编辑
To display the timer too (improved version, thanks to davin too):
也显示计时器(改进版,也感谢 davin):
<button onclick="onTimer()">Clickme</button>
<div id="mycounter"></div>
<script>
i = 60;
function onTimer() {
document.getElementById('mycounter').innerHTML = i;
i--;
if (i < 0) {
alert('You lose!');
}
else {
setTimeout(onTimer, 1000);
}
}
</script>
......
......
回答by Flambino
function timedOut() {
alert("Some error message");
}
// set a timer
setTimeout( timedOut , 60000 );
That basically sets a timer that will execute the given function after 60.000 miliseconds = 60 seconds = 1 minute
这基本上设置了一个计时器,它将在 60.000 毫秒 = 60 秒 = 1 分钟后执行给定的功能
Edit: here's a quick, imperfect fiddle that also shows the countdown http://jsfiddle.net/HRrYG
编辑:这是一个快速、不完美的小提琴,它也显示了倒计时http://jsfiddle.net/HRrYG
function countdown() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "0:" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
}
// start the countdown
countdown();
回答by qw3n
You will want to use the setTimout function check out this article. https://developer.mozilla.org/En/Window.setTimeoutRemember the timer is in milliseconds so for one minute is 60,000.
你会想要使用 setTimout 函数查看这篇文章。 https://developer.mozilla.org/En/Window.setTimeout请记住计时器以毫秒为单位,因此一分钟是 60,000。
回答by Narendra Maurya
// this is the simplest way to one mint counter .this is also use in angular and oops
// 这是一个薄荷计数器的最简单方法。这也用于 angular 和 oops
var i=60;
function coundown(){
setInterval(() => {
if (this.i == 0) {
return;
}
console.log(this.i--);
}, 1000);
}
// this function you can call when otp is comming or form submit and waiting for otp countdown
// 这个函数可以在 otp 到来或表单提交等待 otp 倒计时时调用