javascript/jquery中的停止函数执行
是否可以在单击按钮或任何其他事件时停止javascript中函数的执行?以下是我的困境javascript/jquery中的停止函数执行,javascript,jquery,function,callback,setinterval,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 (itera
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);
}
函数drop(){
setTimeout(函数(){//调用循环时调用250ms setTimeout
setMarkers(映射、locationArray、locationNameArray、迭代器);
迭代器++;
if(迭代器
此功能以250ms的间隔在我的画布上放置Google maps PIN。现在,如果用户想要导航到上一个屏幕(远离地图页面),单击后退按钮我想停止执行这个drop()函数,重置计数器(迭代器)并返回
你知道我该怎么做吗?如果可能的话?
谢谢 最简单的方法是在其中抛出一个“全局”范围的变量,并在每次迭代中检查它
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);
}
如果用户单击后退按钮,将使他们离开当前页面,这将自动停止当前页面上的JS运行。重置
迭代器
似乎有点多余,因为它甚至在上一页(重新)加载后就不存在了……非常感谢!非常简单有效的实现。该死,为什么我以前没想到
$("#mybutton").click(function() {
cancel = true;
});