[英]Run a function repeatedly 10 seconds after it has completed (JavaScript)
我有一个函数使用“ post”从服务器获取数据并进行处理。 数据量各不相同,该功能可能需要很长时间才能完成(30秒)。 我希望该函数被重复调用,但是在完成上一次迭代后仅10秒。 *函数结果存储在全局变量中,并在同一函数的下一次迭代中使用。 我已经尝试过setInterval和setTimeout,但是似乎都没有给我我想要的结果。 有什么想法吗?
function foo(){
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
// do your stuff with returned data
// and call itself again...
setTimeout(foo, 10000);
});
}
这种方法行不通吗?
function a(){
//do stuff
setTimeout(a, 10000); //has to be at the end of the execution. If you're doing things asynchronously that's a different story.
}
函数setTimeout()可以用于此目的。 但是必须先调用该方法,然后函数本身才能再次调用该方法。
function method(){
console.log('method invoked');
setTimeout(method, 10000);
}
method();
var $id = 1;
var Interval ;
$(function(){
callAjax();//Starts Interval
});
functoin callAjax()
{
Interval = setInterval(function () {
try {
if($id > 0)
{
$.ajax({
url: _MyUrl + $id,
success: function (calbkData) {
$id = 0;
if (parseInt(calbkData.id) > 0) {
$id = calbkData.id;
OpenMsg(calbkData.id);
}
},
global: false, // this makes sure ajaxStart is not triggered
dataType: 'json'
//,complete: longpoll
});
}
} catch (e) {
// alert(e);
}
}, 10000);
}
对我来说,这很好。
function Test()
{
//Your code here
setTimeout(Test(),10000);
//Its used to set time interval after your iteration is run
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.