在javascript/jquery中停止执行函数

are*_*s05 2 javascript jquery function callback setinterval

是否可以通过单击按钮或任何其他事件来停止javascript中的函数执行?以下是我的困境

function drop() {

    setTimeout(function () {    //  call a 250ms setTimeout when the loop is called
       setMarkers(map, locationArray, locationNameArray, iterator);
       iterator++;
       if (iterator < locationArray.length) {      //  if the counter < 10, loop!
         drop();             
       }
     }, 250);
}
Run Code Online (Sandbox Code Playgroud)

此功能以250毫秒的间隔删除画布上的Google地图图钉.现在,如果用户想要导航到上一个屏幕(远离Map页面),单击后退按钮我想停止执行此drop()函数,重置计数器(迭代器)并返回.

知道如何做到这一点,或者它是否可能?谢谢!

McG*_*gle 7

最简单的方法是在其中抛​​出一个"全局"范围的变量,并在每次迭代时检查它.

var cancel = false;
function drop() {
    setTimeout(function () {    //  call a 250ms setTimeout when the loop is called
       setMarkers(map, locationArray, locationNameArray, iterator);
       iterator++;
       if (iterator < locationArray.length && cancel === false) {      //  if the counter < 10, loop!
         drop();             
       }
     }, 250);
}
Run Code Online (Sandbox Code Playgroud)

然后在事件处理程序中更新相同的变量:

$("#mybutton").click(function() {
    cancel = true;
});
Run Code Online (Sandbox Code Playgroud)