jQuery 你如何在javascript中每5秒运行一次函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19777371/
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 you run a function every 5 seconds in javascript
提问by user1471980
I am trying to create a javascript which if I click on a div1, I need load_data1() function to refresh every 5 seconds. If the user clicks on div2 or div3, I need load_data1() function to stop. As the code below, when I click on the div1, load_data1() function runs after 5 second and stops, it does not run after that, any ideas what I might be missing here?
我正在尝试创建一个 javascript,如果我点击 div1,我需要 load_data1() 函数每 5 秒刷新一次。如果用户点击 div2 或 div3,我需要 load_data1() 函数停止。如下面的代码,当我点击 div1 时,load_data1() 函数在 5 秒后运行并停止,之后它不会运行,任何想法我在这里可能会遗漏什么?
$(document).ready(function(){
$.ajaxSetup({ cache: false });
var timeout;
function timeout_init() {
timeout=setTimeout('load_data1()', 5000);
return timeout;
}
$("#div1").click(function() {
timeout_init();
});
$("#div2").click(function() {
clearTimeout(timeout);
load_data2();
});
$("#div3").click(function() {
clearTimeout(timeout);
load_data3();
});
});
回答by monastic-panic
you want to use setInterval()instead of setTimeoutwhich only fires the one time, setIntervalwill keep firing until you clear it
您想使用setInterval()而不是setTimeout只触发一次,setInterval将继续触发直到您清除它
回答by Andrei CACIO
You can try something like this:
你可以尝试这样的事情:
window.setInterval(function(){
/// call your function here
}, 5000);
It's an anonymous function that will run every 5 seconds.
这是一个匿名函数,每 5 秒运行一次。

