如何清除函数内的setInterval? [英] How do I clear this setInterval inside a function?

查看:208
本文介绍了如何清除函数内的setInterval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Normally, I’d set the interval to a variable and then clear it like var the_int = setInterval(); clearInterval(the_int); but for my code to work I put it in an anonymous function:

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); 可以肯定,但是没有用。

How do I clear this? I gave it a shot and tried var test = intervalTrigger(); clearInterval(test); to be sure, but that didn’t work.

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

Basically, I need this to stop triggering once my Google Map is clicked, e.g.

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


推荐答案

setInterval 方法返回一个可用于清除间隔的句柄。如果你想让函数返回它,你只需返回方法调用的结果:

The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:

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

这篇关于如何清除函数内的setInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆