Ensuring that the latest changes made by the user on my web application are saved to the database is crucial. To achieve this, I have a function that sends the data to the database when the user closes the page:
window.onbeforeunload = sendData;
However, a problem arises when I try to send data every 10 seconds. Since the requests are sent synchronously (to ensure they are sent during onbeforeunload
), it causes delays in the user interface.
setInterval(sendData,10000);
Here is the function that is being called:
function sendData(){
var xhr = new XMLHttpRequest();
var localData = datatodatabase;
xhr.open("POST", "handler.php", false);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("pack="+datatodatabase);
}
Is there a way to optimize this by utilizing a Web Worker to prevent the synchronous requests from affecting the rest of the application?
(Please note: Synchronous requests are required due to onbeforeunload
)