I have a jQuery each loop with an ajax function inside but I'm experiencing an issue when trying to navigate away from this page while the loop is still running, basically I can't navigate to any other page unless the each loop has finished.
I don't need this loop to finish because it's basically only needed as a visual indicator, its far from being so important to sacrifice user experience for.
$.each( get_link, function( i, val ) {
$(window).on("beforeunload", function() {
return false;
});
$.ajax({
type: "POST",
url: url,
async: true,
data: {url: val},
success: function(data)
{
let row = $("#status[data-url='" + val + "']");
row.html(data);
$("#loader[data-url='" + val + "']").removeClass("loader vertical-align-middle loader-bounce");
}
});
});
As you can see I have tried to fix it with $(window).on("beforeunload")
but beforeunload
creates an unnecessary alert window which unfortunately I couldn't find a way to disable.
EDIT: The above code isn't breaking the loop either...
Is beforeunload
a good idea? Maybe there are better approaches to break a loop on page exit?
f.khantsis suggested to abort the ajax operation which is a good idea but it doesn't help because I run an each loop on an array with 5-6 keys. So if one of them is aborted the loop just goes on to run with all the remaining keys.