Currently, my JavaScript is set up to send data to a server when the page closes using synchronous AJAX (SJAX) request in `window.onbeforeunload`. However, this approach can cause the browser to freeze if the server or network connection experiences delays.
According to what I have researched, it is not possible to specify a timeout for synchronous AJAX requests. Asynchronous AJAX requests do not function properly on `window.onbeforeunload`. My proposed solution would be to use an asynchronous request and then momentarily lock up the browser to ensure that the request completes:
window.onbeforeunload = function() {
doSomeAjax(); // asynchronous request
var now = new Date();
var time_limit = now.getTime()+2000; // 2,000 ms
while(now.getTime() < time_limit) {
now = new Date();
}
}
Would this method be effective? Are there any potential issues to consider?