Initiate a timeout mechanism upon accessing the URL

One approach that we have been using to trigger a URL through ajax involves receiving the response immediately after hitting the URL. However, there is now a requirement to implement a timeout for the response. This means that if the response does not arrive within 2 seconds of invoking the URL, another method should be called. On the other hand, if the response comes back within two seconds, a different method should be executed instead. Despite our attempts at incorporating the timeout feature, we have encountered difficulties in getting it to function properly with the current code.

  function ajaxCall(url1) {
      var ajaxresp = null;
      var xmlhttp;
      if (window.XMLHttpRequest) {
          xmlhttp = new XMLHttpRequest();
      } else {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.open("GET", url1, true);
      xmlhttp.send();
      xmlhttp.onreadystatechange = function () {
          if (xmlhttp.readyState == 4) {
              if (xmlhttp.status == 200) {
                  ajaxresp = xmlhttp.responseText;

                  //function call
                  getAdResponse(ajaxresp);
              }
          }
      }
  }

We are seeking advice on how best to proceed given this scenario.

Answer №1

Consider implementing something along these lines

xmlhttp.open("GET",url1,true);

xmlhttp.onreadystatechange= function (){    
if (xmlhttp.readyState==4){     
    if (xmlhttp.status == 200){     
        ajaxresp = xmlhttp.responseText; 
    }
}
xmlhttp.send();
setTimeout(function() {
    if(ajaxresp) {
       carryOutFunctionA(ajaxresp);
    } else {
       carryOutFunctionB();
    }
}, 2000);

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

There seems to be a request for an unknown parameter '1' in the data table row

My Datatable is structured as follows: <br><button id="addRow">Add New Row</button><br> <table class="table table-striped table-bordered table-hover " id="example" cellSpacing=0 width="100%"> <the ...

What could be causing my function to fail <object>?

Within index.php, I am calling the function twice, which includes chart.html. index.php chart_line($valuesNight); //first call chart_line($valuesEvening); //second call ?> <?php function chart_line($jsonDataSource){ ?> < ...

``The Art of Handling REST API with Express and Mongoose

Running Express on my application, I have a delete route set up as shown below: router.route('/lists/:id') .delete(function(req, res){ Entry.remove({ _id: req.params.id }, function(err, list){ if(err) ...

Introducing random special characters into currency symbols during the process of exporting data to a CSV file

I'm encountering a strange issue when exporting data to CSV files that contain a currency symbol. An extra junk character is being added to the data alongside the currency symbol. For example, if my data is: France - Admin Fee 1 x £100 The result I& ...

Using Vue components in NativeScript-Vue popups: A comprehensive guide

To initiate the popup, I include the following code in a root component: import parentt from "./parentt.vue"; . . . this.$showModal(parentt, { fullscreen: true, }); The contents of parentt.vue are as follows: <template> <StackLayout> ...

Requesting data from server using Ajax with multiple JSON responses

I'm facing a situation where my Ajax script calls a PHP file to make a query to MySQL and then formats the response in JSON. The challenge is that I need to retrieve data from different tables based on the id sent with the Ajax call. Some tables retur ...

Set up Node.js application to allow CORS for designated endpoint(s) exclusively

I am currently facing a dilemma with my Node application and how to handle cross-origin resource sharing. In the past, I have used a PHP proxy to bypass this issue when calling endpoints from JavaScript/AJAX. However, I am now looking to streamline the pro ...

How to dynamically update an API in a single-page VueJS application without requiring a full page reload when new data is submitted

I recently created a one-page system for school administration, which includes several student records. Interestingly, when new data is inputted, the changes are reflected in the database but do not update other components until I manually refresh the pa ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Issue encountered when attempting to modify the directive when the drop-down list is changed in AngularJS

Experiencing issues updating the directive when the drop down list is changed using AngularJS. Below is my application code: HTML Code <div ng-app="myApp" ng-controller="MyCtrl"> <select ng-model="opt" ng-options="font.title for font in font ...

Guide to adding checkbox IDs and inserting them into a textarea

Hello, my name is Prasath and I am currently learning about AJAX. I am working on a project involving seat layouts and finding it challenging to retrieve both the seat fare and seat number simultaneously. Is there anyone who can assist me in resolving this ...

What is the best way to invoke a function using a string as its name?

In my grid configuration function, I am assigning column definitions. One key, valueGetter, requires a function to be called to fetch the column value. The issue I am encountering is that the API returns this value as a string. When I try to set it using ...

A guide on successfully transferring JSON Data to an Express REST API

Currently, I am in the process of developing a REST API with Node/Express and have a query regarding the setup of the API along with integrating a JSON file. As an illustration, the JSON data that I wish to reference consists of an ID number, model, and co ...

The connection was refused by hapi.js

We have recently encountered an issue while using hapijs: hapi, {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","domainEmitter":{"domain":{"domain":null,"_events":{},"_maxListeners":10,"members":[]},"_events":{},"_maxListeners":10},"doma ...

Trouble with the 'uppercase' package in Node.js: Receiving ERR_REQUIRE_ESM error while utilizing the require() function

I am encountering a problem with the 'upper-case' module while developing my Node.js application. My intention is to utilize the upper-case module to convert a string to uppercase, but I'm running into difficulties involving ESM and require( ...

The disappearance of the Jquery Datatable following a change in the selected index of a dropdownlist within an ASP.NET

I implemented the jQuery library into my gridview and it proved to be quite useful. Initially, the datatable displayed perfectly on page load. However, upon changing the value of the dropdown list, the jQuery datatable disappeared. In this scenario, the gr ...

Uploading Massive Form Data Using Angular JS

After spending countless hours on this project, I still can't figure out how to post data into a table using JavaScript objects. While I can easily work with smaller data sets, I'm struggling with handling multiple nested objects. EDIT: ...

Updating device information in real-time using React Native

Currently, I am utilizing react-native-device-info to access the DeviceLocale or DeviceCountry. However, I am wondering if there is a method to update Device-info without requiring a complete restart of the app. For instance, when my device language is se ...

What is the best way to configure my ajax function to send data to a specific PHP POST endpoint?

Hello, I need help figuring out how to configure my ajax request to POST data to a specific PHP endpoint. Here is the code snippet I'm working with: $.ajax({ var feeds = $("#feeds ul"); var last_time = feeds.children().last().attr('id&ap ...

Using an expression from the parent controller to disable an item in an AngularJS directive

I created a list of custom directive items, each with a remove button. The issue I'm facing is that I want to disable the remove button when there's only one item left in the list, but it's not working as expected. To see this problem in ac ...