如何清除函数内部的setInterval?

2020/10/26 15:42 · javascript ·  · 0评论

通常,我会将间隔设置为一个变量,然后像清除变量一样,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地图后停止触发,例如

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

然后清除间隔:

window.clearInterval(id);
// 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);
  }
}
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;  
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p id="counter">&nbsp;</p>
<button id="pauseInterval">Pause/unpause</button></p>
本文地址:http://javascript.askforanswer.com/ruheqingchuhanshuneibudesetinterval.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!