Is it possible to utilize AJAX requests within Web Workers?

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)

Answer №1

Have you considered implementing an asynchronous function that runs every 10 seconds, but switches to synchronous when using onbeforeunload? Here's an example:

setInterval(function () {
    sendData(true);
}, 10000);

window.onbeforeunload = function () {
    sendData(false);
}

function sendData(async) {
    // Adjust the ajax call method based on the value of *async*

    // Potentially in the future:
    xhr.open("POST", "handler.php", async);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The use of HTML5 required attribute is ineffective when submitting forms via AJAX

Seeking advice on implementing basic validation for a newsletter form that only requires an email address. The current page layout doesn't allow space for jQuery error messages, so I attempted to use the HTML 5 required attribute. However, the form st ...

What is the most efficient way to dynamically alter the position of a div element within an HTML document using

In a scenario where a parent div contains multiple child divs, it is required that one particular child div named .div_object_last always stays at the end. Below is an example setup : HTML <div class="div_parent"> <div class="div_object"> ...

Customizing the "Actions" Dropdown in APEX Interactive Grid

Is there a way to modify the choices available in the Selection section of a Row Actions Menu in Apex? I managed to alter the options in the Line Menu, but I'm facing challenges when trying to make changes in the Selection Menu. The Selection Menu i ...

How to select a DOM element in Angular 2.x

Although it may seem simple, there are not many examples of using Angular 2.0 yet. In one of my components, I have a situation where I need to add a class to the body tag. However, my application is bootstrapped deeper than the body element, so I am looki ...

extract element from a string with the help of jquery

When using AJAX to request HTML from a page, the process involves sending a request like this: function getHTML() { //set ajax call var options = { url: '/Controller', type: 'GET', d ...

Tips for defining a function without an arrow as a parameter

Understand that there may be individuals quick to flag this as a duplicate question, but trust me when I say that I have exhaustively searched on Google for almost an hour before turning to ask here. methods: { stylizeHeader: debounce(event => { ...

Unusual shift in behavior - <input> on Windows 8.1

Our application is a unique HTML5/WinJS Google Talk app tailored for Windows 8 users. Within our app, we utilize a textarea for chat input with a predefined maximum height. We have coded the height to automatically adjust to the maximum limit once reached. ...

Exploring the capabilities of ExcelJS for reading xlsx files within an Angular environment

I'm trying to access a source file, make some changes to it, and then provide it for the user to download. However, I am facing an issue with reading the source file from my project directory. Below is my implementation using excelJS for file reading: ...

Diving into Discord.JS - Is there a way to check if a specific message content exists within an array?

I'm currently working on developing a Discord user verification bot that generates a 2048-bit key upon joining a server. This key will be crucial for verifying your account in case it gets compromised or stolen, ensuring that the new account belongs t ...

Encountering a connection error when trying to access a Google spreadsheet within a Next.js application

I am currently exploring Next.js and attempting to utilize Google Sheets as a database for my project. Although my application is functioning correctly, there is still an error message displaying that says "not forgot to setup environment variable". I have ...

Javascript detecting key press event only firing once when a key is continuously held down

I have implemented the code below to redirect to a specific page when the w, s, a, d keys are pressed. <script> document.addEventListener('keydown', function(e){ e = e || window.event; key = e.keyCode || e.charCode; var keys = { 87: &ap ...

unable to assign values to this.props (appears as undefined or an empty array)

Upon setting up react/redux, I encountered a peculiar issue. When my component mounts, it should render the information stored in this.props.heroes.data. However, upon logging this data, I receive an unexpected value of [{id:1,heroname:'Batman',r ...

Resetting initial values with Velocity.js post-animation

After animating elements into view on a page, I want to defer further animation through CSS classes. However, Velocity keeps all animated properties in the style= tag, hindering CSS transitions. My solution involves resetting the CSS upon completion, but ...

What is the best way to have a div created by JavaScript automatically expand to cover the entire screen after clicking on a dynamically generated table cell?

A unique interactive game inspired by Jeopardy is in the works. By clicking on a specific element within the game board, players can reveal questions fetched from the Jeopardy API. These questions are then presented elegantly within a dynamically created d ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

Fade in and out a Div with a distinct class and ID

I'm currently experiencing a minor issue with some jQuery code. Below are some divs: <div class="add" id="1">Follow</div> <div class="added" id="1">Following</div> <div class="add" id="2">Follow</div> <div clas ...

The error "ReferenceError: process is not defined in vue 3" is being

<script setup> import puppeteer from 'puppeteer'; const onChange = async () => { // Initializing the puppeteer library const browser = await puppeteer.launch(); // Creating a new page const page = await browser.newPage(); / ...

Is it possible to refresh the JSViews data that is underneath using an onclick event?

I have created a photo gallery using a JSViews template which includes upvote and downvote buttons. When these buttons are clicked, it triggers a database update to increase the score. However, I am facing an issue with updating the Score field in the HTML ...

Experiencing difficulties in linking Node JS to the local Mongo DB

Currently I am deepening my knowledge in Mongo DB, Mongoose, and Node JS, however, I am facing issues connecting my Node JS to the local Mongo DB. Below is the code snippet I am working with: dbtest.js var express = require('express'); ...

React JS functionality does not support Bootstrap tooltips

I'm attempting to implement a tooltip in my React app, but I'm experiencing issues with it not displaying properly. I am utilizing vanilla Bootstrap for this purpose. I've included the following script tag in my index.html file to import the ...