如何清除函数内的setInterval?

问题描述 投票:161回答:4

通常,我将间隔设置为变量,然后像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();

我该如何清除这个?我试了一下并尝试了qazxsw poi,但这没用。

基本上,我需要这样才能在点击Google地图后停止触发,例如

var test = intervalTrigger(); clearInterval(test);
javascript settimeout dom-events
4个回答
259
投票

google.maps.event.addListener(map, "click", function() { //stop timer }); 方法返回一个句柄,您可以使用该句柄来清除间隔。如果希望函数返回它,只需返回方法调用的结果:

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

10
投票
window.clearInterval(id);

1
投票
// 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);
  }
}

-4
投票

我能想到的最简单的方法:添加一个类。

只需添加一个类(在任何元素上)并在区间内检查它是否在那里。我相信,这比任何其他方式更可靠,可定制和跨语言。

the_int=window.clearInterval(the_int);
var i = 0;
this.setInterval(function() {
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
    console.log('Counting...');
    $('#counter').html(i++); //just for explaining and showing
  } else {
    console.log('Stopped counting');
  }
}, 500);

/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
    $(this).addClass('pauseInterval');
  },function() { //mouse leave
    $(this).removeClass('pauseInterval');
  }
);

/* Other example */
$('#pauseInterval').click(function() {
  $('#counter').toggleClass('pauseInterval');
});
body {
  background-color: #eee;
  font-family: Calibri, Arial, sans-serif;
}
#counter {
  width: 50%;
  background: #ddd;
  border: 2px solid #009afd;
  border-radius: 5px;
  padding: 5px;
  text-align: center;
  transition: .3s;
  margin: 0 auto;
}
#counter.pauseInterval {
  border-color: red;  
}
© www.soinside.com 2019 - 2024. All rights reserved.