Stop function execution in javascript/jquery

11,611

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;
});
Share:
11,611
ares05
Author by

ares05

Updated on June 14, 2022

Comments

  • ares05
    ares05 almost 2 years

    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

    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.

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

  • ares05
    ares05 almost 12 years
    Thanks a lot! Very simple and effective implementation. Damn, why didn't I think of that before