I am looking for a way to stop a loop with a click event(sort of panic button). If you click the button it should stop immediately.
// basic idea
$.each(someArray, function(index, value){
setTimeout(function(){
console.log(index);
},5000*index);
});
$('#panic-button').click(function(){
//the code that should stop the looping
}):
You can’t interrupt the
$.eachloop with aclickhandler once the loop has started. JavaScript execution is single-threaded, so theclickhandler will at best be queued up for the next time the thread is free — after the loop has finished.However, as timers are executed asynchronously, you can cancel them by keeping and clearing each of their IDs: