Javascript synchronously making an AJAX request that times out

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?

Answer №1

The issue you're facing is the browser freezing, and attempting to resolve it by intentionally causing the browser to freeze in a loop. Unfortunately, this approach will also freeze the UI thread, making it not just a potential problem but a definite one.

If the browser is being closed because there's no need for feedback from AJAX responses to update the soon-to-be-closed page, then injecting IMG tags into a hidden DIV with their src properties set to the desired URL could be a possible solution.

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

After running the command "npx/npm create-react-app hello" to create a react app, I received the following message

Whenever I try to execute this command for creating a React app: C:\WINDOWS\system32> npm i create-react-app -g hello I receive the following message in my cmd prompt: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf ...

The Vue3 call fails to retrieve any data from the ipcRender.once function, returning an

Within my preload script, the following code snippet is present: import { contextBridge, ipcRenderer } from 'electron'; contextBridge.exposeInMainWorld('electron', { func: (//redact) => { const input = { //redact ...

Reorganizing an array of JSON data by date value with a limitation to just one

Currently, I am attempting to organize a JSON array based on the date key. However, it appears that my sorting function is either stopping after one sort or simply not functioning correctly. Here is the JavaScript code for my sorting function: function ...

Typescript method fails to compile due to an indexing error

Imagine you're trying to implement this method in Typescript: setResult(guId: string,fieldname: string, data:Array<UsedTsoClusterKey>) { let octdctruns: OctDctRun[] = [...this.octDctRuns]; const index = octdctruns.findIndex((o) => o.guid ...

Display a <div> based on the database query for the portal field

I am new to JavaScript and have been successfully using the code below with a checkbox. function showAddress() { var objectAddress = document.getElementById("objektadresse"); var addressToShow = document.getElementById("adresseeinblenden"); addr ...

Combining several select components in Tapestry 5.3 for dynamic updates (Ajax)

I am currently utilizing tapestry 5.3.7 and I am aiming to implement Ajax chaining select form elements. This means that when one option is selected in a select element, another select element should appear based on the initial choice. I have tried a sampl ...

Refreshing a jQuery droplist

I encountered an issue with a dropdown menu on my webpage. The dropdown menu is supposed to save the selected option to a database when a user clicks "Save." However, when revisiting the page, the dropdown does not display the previously saved value; inste ...

To ensure a successful redirection process without information loss, it is essential to address any potential issues with data input into

How can I properly implement a page redirection? Below are the relevant code snippets. <link rel="stylesheet" type="text/css" href="payout.css"/> <font face='calibri'> <?php session_start(); $conn = @mysql_connect("localho ...

Retrieve the JavaScript blob's file name without including a hyperlink

How can I customize the filename of a blob file in JavaScript when using window.location to force download it? function createCustomFile(data) { var json = JSON.stringify(data); var blob = new Blob([json], {type: "octet/stream"}); var ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...

Attempting to verify the existence of a value in an SQL table prior to insertion

I have a simple table that contains an ID column and a location name column. Additionally, I have created an HTML form where users can input a new location into the table. Before adding the new location, I want to check if that location already exists in m ...

How can I append a variable to the URL parameter in a jQuery $.get

I have been struggling with the $.get function in jQuery. My objective is to achieve something like this: $("#button").click(function(){ var value = $("#textfield").val(); alert(value); $.get('lookup.php?s=<?php echo $id ?>&q=' + value ...

Having trouble populating form with JSON data. It's not appearing

Currently, I am experimenting with jsfiddle to troubleshoot an issue that is possibly unrelated to React.JS. The problem involves populating form fields with data stored in a JSON file. You can view the fiddle here: https://jsfiddle.net/vp5kLxgs/ I am op ...

Modifying the display toggle functions

How can I toggle between a button and an input type "file" when clicked? I am using jQuery to show and hide elements, but I need help changing back to the button when clicking somewhere else on the page. HTML: Upload<input type="button" id="upload" /& ...

The YouTube-Search NPM module is producing unexpected outcomes

I recently integrated the youtube-search NPM library with express to fetch the first youtube video based on a song name. app.get("/search", (req, res) => { var search = require("youtube-search"); var SONG = req.query.SONG; var opts = { maxR ...

Creating a periodic updater in Prototype.js that will hide elements of a specific class based on the response from an AJAX request

I am currently working on a Periodical Updater using prototype js, and my goal is to hide every element on the page with the class='robot' based on the response received from an AJAX request. If the response matches hidethemall, I want all elemen ...

Text being enveloped in a span tag

Currently, I have a table displaying a list of users with their corresponding roles. However, the roles column is sometimes wrapping before reaching the end of the line. The user list data looks like this: $scope.userList = [{ "id": 1, "name":"AB ...

Overriding filters in AngularJS and injecting dependencies into modules

My application relies on two filter modules: var app = angular.module('MyApp',['Filter1','Filter2']); Both modules contain filters with the same name: var filterapp1 = angular.module('Filter1',[]); filterapp1.f ...

How to eliminate spacing between slides in a 3D Carousel Slider using Bootstrap 5

My website utilizes Bootstrap along with a carousel slider, which is functioning properly. However, I am encountering an issue when the slider transitions from right to left. It briefly displays a white space between slides, which I wish to eliminate. I wa ...

Limit Google Places auto complete to display only addresses designated for residential use

I'm in the process of developing an application that utilizes the Google Places autocomplete API. However, I specifically want to restrict user input to only residential addresses, excluding businesses and points of interest. Despite going through the ...