Javascript 如何将函数调用延迟 5 秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4738595/
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 do I delay a function call for 5 seconds?
提问by Webnet
I want widget.Rotator.rotate()
to be delayed 5 seconds between calls... how do I do this in jQuery... it seems like jQuery's delay()
wouldn't work for this...
我想widget.Rotator.rotate()
在调用之间延迟 5 秒...我如何在 jQuery 中执行此操作...似乎 jQuerydelay()
对此不起作用...
回答by BrunoLM
You can use plain javascript, this will call your_func once, after 5 seconds:
您可以使用普通的 javascript,这将在 5 秒后调用 your_func 一次:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
如果你的函数没有参数也没有明确的接收者,你可以直接调用 setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
还有一个我用过一次的插件。它有oneTime
和everyTime
方法。
回答by Phrogz
var rotator = function(){
widget.Rotator.rotate();
setTimeout(rotator,5000);
};
rotator();
Or:
或者:
setInterval(
function(){ widget.Rotator.rotate() },
5000
);
Or:
或者:
setInterval(
widget.Rotator.rotate.bind(widget.Rotator),
5000
);