的JavaScript停止间隔功能异步
问题描述:
我有我的网页下面的脚本:的JavaScript停止间隔功能异步
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;
}
}
这是因为它在执行异步阿贾克斯后多次触发。我怎样才能避免这种情况?
编辑
我更新了我用的是代码的问题,忘了补充调用clearInterval。我现在意识到这是ajax在一秒钟内没有响应,并且函数被再次调用。
答
它与异步无关。
您应该使用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;
}
}
答
它会多次触发AJAX调用,因为当您不再需要它时不会停止该时间间隔。它将继续倒计时,并且每次都会进行AJAX调用,因为条件将继续保持为真。
获取句柄他区间在启动时:当你想停止它(AJAX调用之前)
var bountyInterval = setInterval(checkBounty, 1000);
然后,使用clearInterval
方法:
clearInterval(bountyInterval);
答
清除间隔破坏定时器
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请求不是因为它异步执行,而是因为它是异步执行的这是其行为 – micnic 2013-04-20 11:18:09