如何停止定时器,如果功能执行正确

How to stop timer if function executed properly?

本文关键字:执行 功能 如果 何停止 定时器      更新时间:2023-09-26

Section()负责查看数据库并获得任何HTML代码,如果某些内容匹配。如果没有匹配,则没有回调(但我可以回调一个空的对象)。

然后调用addIt()并显示HTML。没问题。

我的问题是,当有一些HTML从数据库中获取,停止定时器?因为现在它每10秒添加一次HTML。

function addIt(data) { $(data).insertAfter('#hello'); }
setInterval(function Section(){
      $.getJSON("domain"+ number, addIt);
}, 10000);

可以这样写:

var x = setInterval(function Section(){
  $.getJSON("domain"+ number, addIt);
}, 10000);
if( // something ) {
   clearInterval(x);
 }

我永远不会在一段时间内调用AJAX。相反,使用回调函数再次调用

function Section(){
   $.getJSON("domain"+number,addIt);
}
function addIt(data) { 
    if (data) $(data).insertAfter('#hello'); 
    else setTimeout(Section,10000); // call again in 10 seconds unless data was returned
}
Section(); // first call

如果调用在不返回数据时导致ERROR,请尝试:

$.getJSON("domain"+number, function(data) {
  if (data) $(data).insertAfter('#hello'); 
})
.fail(function() { 
  setTimeout(Section,10000);
});
var timerId;
function addIt(data) { 
  $(data).insertAfter('#hello');
}
function section() {
  $.getJSON().done(function(data) {
    addIt(data);
    if (timerId) {
      clearInterval(timerId);
    }
  });
}
timerId = setInterval(section, 10000);