使用 jQuery 延迟 JavaScript 函数调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5322344/
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
To delay JavaScript function call using jQuery
提问by Mohan Ram
JavaScript:
JavaScript:
$(document).ready(function(){
function sample() {
alert("This is sample function");
}
$("#button").click(function(){
t = setTimeout("sample()",2000);
});
});
HTML:
HTML:
<input type="button" id="button" value="Call sample function with delay">
Once I click the button, sample()function is not called with a delay of 2 seconds. I don't know what's wrong.
单击该按钮后,sample()不会延迟 2 秒调用函数。我不知道怎么了。
How to call JavaScript function using setTimeout()via jQuery?
如何使用setTimeout()jQuery调用 JavaScript 函数?
回答by Quentin
Since you declare sampleinside the anonymous function you pass to ready, it is scoped to that function.
由于您sample在传递给的匿名函数中声明ready,因此它的范围仅限于该函数。
You then pass a stringto setTimeoutwhich is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.
然后,通过一个字符串到setTimeout这eval2秒后编。这发生在当前范围之外,因此它无法找到该函数。
Only pass functionsto setTimeout, using eval is inefficient and hard to debug.
仅将函数传递给setTimeout,使用 eval 效率低下且难以调试。
setTimeout(sample,2000)
回答by alex
function sample() {
alert("This is sample function");
}
$(function() {
$("#button").click(function() {
setTimeout(sample, 2000);
});
});
If you want to encapsulate sample()there, wrap the whole thing in a self invoking function (function() { ... })().
如果你想在sample()那里封装,把整个事情包装在一个自调用函数中(function() { ... })()。
回答by Fizzix
Very easy, just call the function within a specific amount of milliseconds using setTimeout()
非常简单,只需使用setTimeout()在特定的毫秒数内调用该函数
setTimeout(myFunction, 2000)
function myFunction() {
alert('Was called after 2 seconds');
}
Or you can even initiate the function inside the timeout, like so:
或者您甚至可以在超时内启动函数,如下所示:
setTimeout(function() {
alert('Was called after 2 seconds');
}, 2000)

