停止setInterval

我想停止error处理程序中的这个间隔反复运行。 这是可能的,如果是这样,怎么样?

 $(document).on('ready',function(){ setInterval(updateDiv,3000); }); function updateDiv(){ $.ajax({ url: 'getContent.php', success: function(data){ $('.square').html(data); }, error: function(){ $.playSound('oneday.wav'); $('.square').html('<span style="color:red">Connection problems</span>'); // I want to stop it here } }); } 

您需要将setInterval的返回值设置为click处理程序范围内的variables,然后使用clearInterval()如下所示:

 var interval = null; $(document).on('ready',function(){ interval = setInterval(updateDiv,3000); }); function updateDiv(){ $.ajax({ url: 'getContent.php', success: function(data){ $('.square').html(data); }, error: function(){ clearInterval(interval); // stop the interval $.playSound('oneday.wav'); $('.square').html('<span style="color:red">Connection problems</span>'); } }); } 

使用一个variables并调用clearInterval来停止它。

 var interval; $(document).on('ready',function() interval = setInterval(updateDiv,3000); }); function updateDiv(){ $.ajax({ url: 'getContent.php', success: function(data){ $('.square').html(data); }, error: function(){ $.playSound('oneday.wav'); $('.square').html('<span style="color:red">Connection problems</span>'); // I want to stop it here clearInterval(interval); } }); } 

您必须将setInterval函数的返回值分配给一个variables

 var interval; $(document).on('ready',function(){ interval = setInterval(updateDiv,3000); }); 

然后使用clearInterval(interval)再次清除它。

使用这个我希望能帮到你

 var interval; function updateDiv(){ $.ajax({ url: 'getContent.php', success: function(data){ $('.square').html(data); }, error: function(){ /* clearInterval(interval); */ stopinterval(); // stop the interval $.playSound('oneday.wav'); $('.square').html('<span style="color:red">Connection problems</span>'); } }); } function playinterval(){ updateDiv(); interval = setInterval(function(){updateDiv();},3000); return false; } function stopinterval(){ clearInterval(interval); return false; } $(document) .on('ready',playinterval) .on({click:playinterval},"#playinterval") .on({click:stopinterval},"#stopinterval");