停止间隔函数async

Javascript stop interval function async

本文关键字:函数 async      更新时间:2023-09-26

我的网页上有以下脚本:

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);