停止间隔函数async
Javascript stop interval function async
我的网页上有以下脚本:
tid = setInterval(checkBounty, 1000);
function checkBounty(){
var elapsed = (Date.now()/1000) - parseInt($(".bounty").data('created')) ;
$(".remaining-time").html(valid - elapsed); //update remaining time until bounty expires
if (elapsed> valid){
$.POST('', {id: id}, function(){
console.log ('bounty cancelled');
clearInterval(tid);
});
//do an ajax post to cancel the bounty;
}
}
这会触发ajax post多次,因为它是异步执行的。我怎样才能避免呢?
编辑我用我正在使用的代码更新了问题,忘记添加clearInterval。我现在意识到是ajax在不到一秒的时间内没有响应,函数被再次调用。
与async无关。
如果你只想让它执行一次,你应该使用setTimeout
而不是setInterval
编辑重读问题后,我认为你想要的是这个(如前所述):
var intervalid = setInterval(checkBounty, 1000); // capture the id of the interval
function checkBounty(){
var elapsed = (Date.now()/1000) - parseInt($(".bounty").data('created')) ;
$(".remaining-time").html(valid - elapsed); //update remaining time until bounty expires
if (elapsed> valid){
clearInterval(intervalid); // this stops the timer
//do an ajax post to cancel the bounty;
}
}
清除间隔以销毁定时器
var timer = setInterval(checkBounty, 1000);
function checkBounty(){
var elapsed = (Date.now()/1000) - $(".bounty").data('created') ;
$(".remaining-time").html(valid - elapsed); //update remaining time until bounty expires
if (elapsed> valid){
clearInterval(timer);
//do an ajax post to cancel the bounty;
}
}
它会多次触发AJAX调用,因为当您不再需要它时,您不会停止间隔。当条件仍然为真时,它将继续倒计时并每次进行AJAX调用。
获取启动间隔的句柄:
var bountyInterval = setInterval(checkBounty, 1000);
然后当您想要停止它(在AJAX调用之前)时,使用clearInterval
方法:
clearInterval(bountyInterval);
相关文章:
- jQuery加载的async和ready函数不工作
- 什么'这是从第三个函数上的async 1st函数获得结果的更好方法
- 使用节点确定成功/失败.js函数 async.retry
- Async.waterfall 函数在保存解析对象后退出
- Node.js使用async函数返回的对象
- 使用预定义函数的NodeJS async.series
- 对async函数进行同步调用
- 等待函数结束(在 async.series 中)无法按预期工作
- Async.waterfall 的本机回调函数
- 为什么 JavaScript 函数需要有关键字“async”?“等待”关键字还不够吗?
- 使用从 async.series 调用的原型函数中的“this”
- node.js async.maplimit() 将额外的参数传递给处理函数
- 一个带有 async:true 的 ajax 函数
- 在 async.each 的帮助下调用 foreach 中的同步函数(带回调)
- 异步函数在 Async.map 中的恢复结果
- JavaScript插入带有async的脚本并使用其中的函数
- 混合了sync和async javascript/jquery,并在最后获得了一个成功函数
- javascript删除async.parallel中的函数
- 停止间隔函数async
- 来自You Don't Know JS的Kyle Simpson asyncify函数:Async &表演