Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript停止间隔函数异步_Javascript_Asynchronous - Fatal编程技术网

Javascript停止间隔函数异步

Javascript停止间隔函数异步,javascript,asynchronous,Javascript,Asynchronous,我的网页上有以下脚本: 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

我的网页上有以下脚本:

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在不到一秒钟的时间内没有响应,函数再次被调用

它与异步无关

如果只希望setInterval执行一次,则应使用
setTimeout
而不是setInterval

编辑重读问题后,我认为您想要的是以下内容(如前所述):


它会多次触发AJAX调用,因为当您不再需要它时,不会停止该间隔。它将继续倒计时,并且每次都进行AJAX调用,因为条件将继续为真

启动间歇时,将手柄置于间歇:

var bountyInterval = setInterval(checkBounty, 1000);
然后,当您想要停止它时(在AJAX调用之前),使用
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方法,然后启动计时器呢?在计时器功能中,您应该只更新剩余的time@Kenneth:剩下的时间是在ajax调用完成之前,而不是在等待响应时。因此,如果我没有弄错的话:您需要倒计时。倒计时结束后,您需要执行ajax方法。对吗?@Samson:不,我想他只是把问题搞错了。在文章中使用setTimeout对您没有帮助。它会触发多个ajax请求,不是因为它是异步执行的,而是因为它的行为正确,我应该在进入ajax之前执行clearInterval?@Samson:是的。好的,由于调用是异步的,实际上在之前或之后执行调用并不重要,但是在之前执行调用更符合代码的意图。
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;
  }
}