在 javascript/jquery 中停止函数执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11095064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:04:52  来源:igfitidea点击:

Stop function execution in javascript/jquery

javascriptjqueryfunctioncallbacksetinterval

提问by ares05

Is it possible to stop the execution of a function in javascript on click of a button or any other event for that matter? Following is my dilemma

是否可以在单击按钮或任何其他事件时停止执行 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);
}

This function drops Google maps pins on my canvas at an interval of 250ms. Now if the user wants to navigate to the previous screen (away from the Map page), on click of the back button I want to stop the execution of this drop() function, reset the counter (iterator) and go back.

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

Any idea how I can do this or if its even possible? Thanks!

知道我如何做到这一点,或者甚至可能吗?谢谢!

回答by McGarnagle

The easiest way to do this is to throw a "globally" scoped variable in there, and check for it on each iteration.

最简单的方法是在那里抛出一个“全局”范围的变量,并在每次迭代时检查它。

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

Then update the same variable in your event handler:

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

$("#mybutton").click(function() {
    cancel = true;
});