javascript 如何在 15 秒内每 3 秒调用一次函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8991095/
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 can I call a function every 3 seconds for 15 seconds?
提问by Jonas
How do I call a jQuery function every 3 seconds?
如何每 3 秒调用一次 jQuery 函数?
$(document).ready(function ()
{
//do stuff...
$('post').each(function()
{
//do stuff...
})
//do stuff...
})
I'm trying to run that code for a period of 15 seconds.
我试图运行该代码 15 秒。
回答by Reinstate Monica Cellio
None of the answers so far take into account that it only wants to happen for 15 seconds and then stop...
到目前为止,没有一个答案考虑到它只想发生 15 秒然后停止......
$(function() {
var intervalID = setInterval(function() {
// Do whatever in here that happens every 3 seconds
}, 3000);
setTimeout(function() {
clearInterval(intervalID);
}, 18000);
});
This creates an interval (every 3 seconds) that runs whatever code you put in the function. After 15 seconds the interval is destroyed (there is an initial 3 second delay, hence the 18 second overall runtime).
这会创建一个间隔(每 3 秒),运行您放入函数中的任何代码。15 秒后间隔被破坏(最初有 3 秒延迟,因此总运行时间为 18 秒)。
回答by Rocket Hazmat
You can use setTimeout
to run a function after X milliseconds have passed.
您可以setTimeout
在 X 毫秒后运行一个函数。
var timeout = setTimeout(function(){
$('post').each(function(){
//do stuff...
});
}, 3000);
Or, setInterval
to run a function every X milliseconds.
或者,setInterval
每 X 毫秒运行一次函数。
var interval = setInterval(function(){
$('post').each(function(){
//do stuff...
});
}, 3000);
setTimeout
and setInterval
return IDs, these can be used to clear the timeout/interval using clearTimeout
or clearInterval
.
setTimeout
并setInterval
返回 ID,这些可用于使用clearTimeout
或清除超时/间隔clearInterval
。
回答by Johan
setInterval(function() {
// Do something every 3 seconds
}, 3000);
回答by JaredPar
Use the setInterval
function.
使用该setInterval
功能。
var doPost = function() {
$('post').each(function() {
...
});
};
setInterval(function() { doPost(); }, 3000);
回答by Simon
You could use the setTimeout method also, which supports things like cancelling the timer.
您也可以使用 setTimeout 方法,该方法支持取消计时器等操作。
See: http://msdn.microsoft.com/en-us/library/ie/ms536753(v=vs.85).aspx
请参阅:http: //msdn.microsoft.com/en-us/library/ie/ms536753(v=vs.85).aspx