如何在函数中清除此集合间隔?

2022-08-30 02:10:57

通常,我会将间隔设置为变量,然后像清除它一样,但是为了让我的代码工作,我把它放在一个匿名函数中:var the_int = setInterval(); clearInterval(the_int);

function intervalTrigger() {
  setInterval(function() {
    if (timedCount >= markers.length) {
      timedCount = 0;
    }

    google.maps.event.trigger(markers[timedCount], "click");
    timedCount++;
  }, 5000);
};

intervalTrigger();

如何清除此内容?我试了一下,试图确定,但这不起作用。var test = intervalTrigger(); clearInterval(test);

基本上,我需要这个来停止触发,一旦我的谷歌地图被点击,例如

google.maps.event.addListener(map, "click", function() {
  //stop timer
});

答案 1

该方法返回可用于清除间隔的句柄。如果希望函数返回它,则只需返回方法调用的结果:setInterval

function intervalTrigger() {
  return window.setInterval( function() {
    if (timedCount >= markers.length) {
       timedCount = 0;
    }
    google.maps.event.trigger(markers[timedCount], "click");
    timedCount++;
  }, 5000 );
};
var id = intervalTrigger();

然后要清除间隔:

window.clearInterval(id);

答案 2
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
  console.log('someProcess() has been called');
  // If some condition is true clear the interval
  if (stopIntervalIsTrue) {
    window.clearInterval(intervalListener);
  }
}