在函数完成后10秒重复运行该函数(JavaScript)
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
}
相关文章:
- 关注函数运行过的表单字段(新手)
- 在函数运行时显示对话
- Javascript - 加载函数运行时未定义的变量
- Javascript变量在函数运行后不断重置自身
- 如何让 setTimeout 函数运行,然后停止使用循环
- 如何在函数运行之前隐藏 CSS
- 使用 .on 函数运行 jQuery 声明函数
- 在函数运行期间关闭 onClick
- jQuery停止函数运行两次
- Javascript:如何在函数运行完成之前对文档进行更改
- nodejs - 为什么我的异步函数运行两次
- 在传递值后停止函数运行
- 如何在 javascript 中的函数中将字符串作为函数运行
- 如何停止计时器函数运行
- 在浏览器空闲后保持设置超时函数运行
- JQuery:阻止一个函数运行,直到满足另一个函数条件“X”时间
- Angular 提供程序服务需要 init 函数运行一次
- 更新 Angular $interval 中的变量会导致其他函数运行
- 如何阻止此 setTimeout 函数运行
- 传入函数数组作为参数,对于函数中的每个函数运行函数