JSFiddle - React, Tailwind, and code Playground

HTML

With console opened and "Preserve log" checked, try to refresh the page or press <kbd>"Run"</kbd> to see how this works
<br />
<small>
    1. (Here I do not use ajax)<br />
    2. (Change the "stay" delay on JS line #14, it is 2000 = 2secs)
</small>

JavaScript

jQuery(window).on("unload", function() {
    clearTimeout(stayHere); // This is another assurance that the "stay here"_code is not executed
    console.log("Leave");
});


var stayHere = ""; // this variable helps with the "stay on this page"_code cancellation when user chooses "leave this page"
window.onbeforeunload = userConfirmation;

function userConfirmation() {
    var confirmation = "Your edits will be lost";
    stayHere = setTimeout(function() { // the timeout will be cleared on "leave this page" click
        console.log("Stay");
    }, 2000); // Here you must put the proper time for your application
    return confirmation;
}