setTimeout 延迟不等待超时 [英] setTimeout delay doesn't wait for the timeout
问题描述
我试图将头放在 setTimeout
上,但我无法让它正常工作.
I trying to wrap my head around setTimeout
, but I can't get it to work properly.
我在这里设置了一个示例:http://jsfiddle.net/timkl/Fca2n/一个>
I have set up an example here: http://jsfiddle.net/timkl/Fca2n/
我想要一个文本在点击锚点后倒计时 - 但我的 setTimeout
似乎同时触发,即使我将延迟设置为 1 秒.
I want a text to countdown after an anchor is clicked - but my setTimeout
seems to fire at the same time, even though I've set the delay to 1 sec.
这是我的 HTML:
<a href="#">Click me!</a>
<span id="target"></span>
这是我的 JS:
$(document).ready(function() {
function foo(){
writeNumber = $("#target");
setTimeout(writeNumber.html("1"),1000);
setTimeout(writeNumber.html("2"),1000);
setTimeout(writeNumber.html("3"),1000);
};
$('a').click(function() {
foo();
});
});
推荐答案
setTimeout
将函数作为参数.您正在执行该函数并将结果传递给 setTimeout
(因此该函数会立即执行).您可以使用匿名函数,例如:
setTimeout
takes a function as an argument. You're executing the function and passing the result into setTimeout
(so the function is executed straight away). You can use anonymous functions, for example:
setTimeout(function() {
writeNumber.html("1");
}, 1000);
请注意,setInterval
也是如此.
这篇关于setTimeout 延迟不等待超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!