Search timeout restriction

I have a function that makes a request to the server to retrieve data.

Here is the code for it:

export default class StatusChecker {
  constructor() {
    if (gon.search && gon.search.searched) {
      this.final_load();
    } else {

      this.make_request(this);
    }
  }


  private make_request(context: StatusChecker) {
  let myrequest;
  myrequest = $.ajax({
      url: "/search/status",
      type: "GET",
      context: context,
      data: {
        search_id: gon.search["id"]
      },
      success: this.handle_response,
      error: this.handle_response_error
    });
    var t= setTimeout(function(){ myrequest.abort();}, 30000);
  }

  private handle_response(data): void {
    if (data == "ready") {
      this.request_itineraries();
    } else {
      setTimeout(() => this.make_request(this), 500);
    }
  }

  private handle_response_error(): void {
    $("#step_1_ajax_error").fancybox({
      afterClose() {
        return Helpers.navigate("/");
      }
    });
  }

  private request_itineraries(): void {
    $.ajax({
      url: "/search/itineraries",
      type: "GET",
      context: this,
      data: {
        search_id: gon.search["id"]
      },
      success: this.handle_request_itineraries
    });
  }

  private handle_request_itineraries(data): void {
    if (data.html.indexOf("step_1_search_error") > 0) {
      Track.log_event("Show error screen", data.html);
      $.fancybox.open($("#step_1_search_error"), {
        afterClose() {
          if (
            gon.links !== null && 
            gon.links.last_search !== null
          ) {
            return Helpers.navigate(gon.links.last_search);
          } else {
            return Helpers.navigate("/");
          }
        }
      });
    } else {
      // Update gon!
      gon = data.gon;

      $(".step_1_body").html(data.html);
      $("#searching").hide();
      $(".search_box_overlay").hide();
      $(".search_box_overlay_top").hide();

      this.final_load();
    }
  }

  private final_load(): void {
    if (gon.debug_enabled) {
      ItinerariesResult.load_debug();
    }

    Filter.load();
    Banners.load();
    ItinerariesResult.load();

    setTimeout(() => State.hide_searchfield(), 100);
  }
}

However, I encountered the following issue:

The problem arises when the state on the server side remains unchanged, causing an endless search. There needs to be a mechanism in place to give up at some point.

One solution I considered was:

Adding a simple setTimeout of 30 seconds when the search begins. If it triggers after 30 seconds without any change, it should display an error message. If the state changes, then the setTimeout should be removed.

UPDATE

Implementing

var t= setTimeout(function(){ myrequest.abort();}, 30000);
will not resolve the issue because:

The underlying problem occurs when the server consistently returns the same result. In such cases, the system gets stuck in a loop.

How can I address this within my code?

Answer №1

Ensure a name is set for ajax requests and implement .abort() function when necessary:

 let shouldRepeat = true;
 let myrequest;

 private make_request(context: StatusChecker) {
      myrequest = $.ajax({
      url: "/search/status",
      type: "GET",
      context: context,
      data: {
        search_id: gon.search["id"]
      },
      success: this.handle_response,
      error: this.handle_response_error
    });

    let t = setTimeout(function(){ 
         myrequest.abort();
         shoudlRepeat = false;}, 30000);

  }

  private handle_response(data): void {
    if (data == "ready") {
      this.request_itineraries();
    } else {
      if (shouldRepeat){
           setTimeout(() => this.make_request(this), 500);
      }
    }
  }

Edit: Additionally, I have included a global boolean shouldRepeat which is initially set to true. When the 30-second timeout is reached, it switches to false, preventing further execution of make_request(this).

Answer №2

function fetch_data(status: CheckStatus) {


    // implementing timeout feature;
    var hasTimedOut = false;
    window.setTimeout( function(){
        hasTimedOut = true;
    }, 30000 );


    $.ajax({
      url: "/get/status/data",
      type: "GET",
      context: status,
      data: {
        status_id: tracking.status["id"]
      },
      success: this.process_response, // check for timeout
      error: this.process_error_response // check for timeout
    });
  }

[UPDATE]

Give this a shot:

var max_attempts = 7;
var current_attempt = 0;

function process_response(data): void {

  if (data == "complete") {
    current_attempt = 0;
    this.retrieve_information();
  } else {
    if( current_attempt < max_attempts ){
      current_attempt++;
      setTimeout(() => this.fetch_data(this), 500);
    }
  }
}

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 method _react.default.useContext does not exist as a function

I am currently working with Material UI Stepper. After using it, I noticed that the functionality is not working properly as expected from their website. To troubleshoot, I added a console.log inside the VerticalLinearStepper method. Upon checking the cons ...

Rendering an element in React Router Dom based on specific conditions

Starting a new project with the latest version of react-router-dom and following their recommendation to use createBrowserRouter. The goal is to display a different header based on the path parameters. Currently, I have set up an optional path parameter: ...

Node.js: retrieving a webpage and waiting for it to load before extracting data

Is it possible to scrape a webpage using just node.js without relying on other libraries like phantom.js? That is the question I have been pondering lately. In my code below, I am requesting a webpage with request and then using cheerio to extract data by ...

What is the best way to manipulate arrays using React hooks?

Struggling with updating arrays using hooks for state management has been quite a challenge for me. I've experimented with various solutions, but the useReducer method paired with dispatch on onClick handlers seems to be the most effective for perform ...

Show side by side using javascript

My dilemma lies in having a set of cards that are meant to be displayed inline, but I have to initially hide them using "display: none". When a specific button is clicked, I aim to reveal these cards; however, upon doing so, each card seems to occupy its o ...

Issue with the react-native-autocomplete-input where the list does not close after selecting an option

After selecting an item from the list in my react-native-autocomplete-input, the list does not close. let Location = (props) => ( <View style={styles.formItem}> <Autocomplete data={props.autocompleteResults.predictions} de ...

What is the correct way to accurately determine the width of a block being displayed with the flex-direction:column property?

For instance: HTML console.log($('.container').width()); // 600px as we defined in css. console.log($('.list').width()); // 600px console.log($('.box').eq('-1').position().left + $('.box').outerWidth( ...

Using NGRX Effects to Load Data for a Specific Item in Angular

On my website, there is a page that displays a range of products from the store managed by a reducer called products. When an action PRODUCTS.LOAD_ALL is dispatched, it triggers an API call through an effect and then sends a PRODUCTS.LOAD_ALL_SUCCESS actio ...

Issues with launching nested Bootstrap accordion panel utilizing jQuery

I am utilizing Bootstrap along with jQuery features. In my accordion group, there is a nested inner accordion group. The HTML code for this can be found in this JS Fiddle link: <h3>Accordion test</h3> <button type="button" class="btn btn-d ...

AngularJS: encountering an issue with undefined vm variable while implementing controllerAs syntax within a directive

I am having trouble accessing the vm.screensize property in the relevant controller. The error message states that vm is not defined. Below you can find the directive and controller code snippets. angular.module('app.ain.directives') .direct ...

Collaborate by sharing local storage with other systems

One of my systems (x.x.x.x: 8000) creates a localstorage after logging in. Now, when a user interacts with another system (x.x.x.x: 8001) by clicking a specific button, the information stored in the initial system's localstorage (x.x.x.x: 8000) is nee ...

The toolbar button in the Froala WYSIWYG editor is mysteriously missing from view

Embarking on a project with Froala editor and Angular 1, I meticulously followed the documentation to show the insertImage button and insertTable, but they are not appearing. Here is my code: var tb = ["bold", "italic", "insertTable", "insertImage"]; $sc ...

There is no such property as formData.delete()

When I am using a FormData object to upload a file, I want to add functionality to delete the file from FormData. However, I encountered an error stating that the delete property does not exist on the FormData object. formData.delete(fileName) Code uplo ...

Navigate a first person simulation using three.js and control your movements with the keyboard arrow

To access my reference material, please go to http://jsfiddle.net/fYtwf/ Overview I am working on a basic 3D simulation using three.js where the camera is surrounded by cubes in three dimensions. These cubes serve as a visual guide to where the camera is ...

Including code that is tailored specifically for the Internet Explorer browser on Windows Phone devices

While testing the Google Maps API on different browsers and devices, I encountered issues with Windows Phone. It turns out that Google Maps is not supported on Windows Phones, resulting in errors. How can I set it up so that instead of displaying the map ...

Encountering a Laravel 419 Error due to CSRF Token verification problem during Ajax request handling

I'm running into a Laravel 419 error when using Ajax and I'm unsure of the cause. I've read in other posts that it might be related to the csrf token, but since I don't have a form, I'm not sure how to resolve this issue. Here&ap ...

The removeEventListener function is failing to properly remove the keydown event

Every time my component is rendered, I attach an event listener. mounted() { window.addEventListener("keydown", e => this.moveIndex(e)); } Interestingly, even when placed within the moveIndex method itself, the event listener persists and cannot ...

Is there a way to check for keys in a TypeScript object that I am not familiar with?

I have a good understanding of the unknown type in TypeScript. I am dealing with untrusted input that is typed as unknown, and my goal is to verify if it contains a truthy value under the key input.things.0. function checkGreatness(input: unknown) { retu ...

How do I determine in Selenium if I have successfully scrolled to the bottom of the page?

Imagine a situation where a list of elements is loaded dynamically in chunks at runtime. Whenever you scroll the page, more data is fetched and displayed. I am currently looking for a way to determine if I have reached the bottom of the page after scroll ...

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...