javascript setTimeout() 不等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15171266/
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
setTimeout() is not waiting
提问by Mike
I am trying to make a seconds countdown with Javascript.
我正在尝试使用 Javascript 进行秒倒计时。
Here is my HTML
这是我的 HTML
<div id="ban_container" class="error center">Please wait
<span id="ban_countdown" style="font-weight:bold">
45</span>
seconds before trying again
</div>
And my JS:
还有我的 JS:
<script type="text/javascript">
var seconds = <?php echo $user->getBlockExpiryRemaining(); ?>;
function countdown(element) {
var el = document.getElementById(element);
if (seconds === 0) {
document.getElementById("ban_container").innerHTML = "done";
return;
}
else {
el.innerHTML = seconds;
seconds--;
setTimeout(countdown(element), 1000);
}
}
countdown('ban_countdown');
</script>
However for some reason, it is not waiting the timeout time, but instead executes countdown
right away so that when I refresh the page it just displays "done" right away. I know it is actually being executed multiple times because if I do innerHTML += seconds + " ";
it counts down from 45. Why is the timeout being bypassed?
但是由于某种原因,它没有等待超时时间,而是立即执行countdown
,以便当我刷新页面时它立即显示“完成”。我知道它实际上被执行了多次,因为如果我这样做,innerHTML += seconds + " ";
它会从 45 开始倒计时。为什么会绕过超时?
回答by Blender
setTimeout(countdown(element), 1000);
executes your function with that argument and passes the result into setTimeout
. You don't want that.
setTimeout(countdown(element), 1000);
使用该参数执行您的函数并将结果传递到setTimeout
. 你不想那样。
Instead, execute an anonymous function that calls your function:
相反,执行一个匿名函数来调用您的函数:
setTimeout(function() {
countdown(el); // You used `el`, not `element`?
}, 1000);
回答by Peter Rasmussen
It is because setTimeout is asynchroneous. Try this:
这是因为 setTimeout 是异步的。试试这个:
setTimeout(function(){
countdown('ban_countdown'); //or elemement
}, 1000);
This will make the function countdown execute after 1000 miliseconds.
这将使函数倒计时在 1000 毫秒后执行。
回答by Doron Kimia
If you'd like to pass an argument to a function by setTimeout
, try this:
如果您想将参数传递给函数 by setTimeout
,请尝试以下操作:
setTimeout(countdown, 1000, element);
The syntax of setTimeout is the following:
setTimeout 的语法如下:
setTimeout(function,milliseconds,param1,param2,...)