Managing numerous Ajax requests: Utilize clearTimeout

I am working with data retrieved from a MySQL request. Each element has a unique id, which is also passed as a parameter to the onclick function.

Every time an element is clicked, it triggers a search in the database for specific data. This process continues until the desired result is obtained. Once the expected answer is received, the function should stop.

My challenge is figuring out how to determine when the expected data has arrived so that I can halt the function. Changing the value of var x leads to an "x is not defined" error.

Answer №1

Set up a collection of intervals

var timeIntervals = {};
function find(id) {
    document.getElementById(id).style.color = "red";
    timeIntervals[id] = setInterval(function () {output(id)}, 1000);
}

function output(id) {
    document.getElementById("result").innerHTML = id;
    /*
    AJAX call to check for an answer

     if(isAnswered)
     {
         clearTimeout(timeIntervals[id]);
     }

    */
}

A preferable approach would be using setTimeout instead of managing the intervals

function find(id) {
    document.getElementById(id).style.color = "red";
    output(id);
}

function output(id) {
    document.getElementById("result").innerHTML = id;
    /*
    AJAX call to check for an answer

     if(!isAnswered)
     {
         window.setTimeout( function () { output(id); }, 1000);
     }

    */
}

Answer №2

You have the issue of declaring X inside the function, making it inaccessible outside of it.

Consider using the following approach instead:

var x; // declare a global variable here
function search(id) {
     document.getElementById(id).style.color = "red";
     return setInterval(function () {answer(id)}, 1000); // return the interval ID
}

function answer(id) {
    document.getElementById("result").innerHTML = id;
    clearTimeout(x);
    /*
    Perform an AJAX request to find an answer.
    
     if(answer)
     {
     clearTimeout(x); // Note that var x is not defined globally
     }
      
    */
}
<div id="one" onclick="x = search('one');"> <!-- Assign X with the interval -->
    click
</div>

<div id="two" onclick="x = search('two');">
    click
</div>

<div id="result">
    
</div>

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

What is the process for incorporating a compiled JavaScript library into a TypeScript project?

In my Typescript project (ProjectA), I am utilizing several node packages. Additionally, I have a babel project (ProjectB) with a build configuration that supports output for multiple module definition standards such as amd, common.js, and esm. My questio ...

The Google Maps JavaScript API is failing to load

While constructing a website that utilizes the Google Maps JS API, I encountered an issue where the map remains blank without any errors appearing in the Google Chrome Console. HTML code: <div id="map-container-5" class="z-depth-1" style="height: 200 ...

Is there a way to incorporate hyperlinks into the Application column of my v-data-table component?

When loading data table from the database, I have included links along with the names of the Applications. However, I only want to display the Application name and open the corresponding link when clicked. headers: [ { text: 'Name&a ...

Guide on How to Add a Save as Button for an Image

I am working on a Chrome Screenshot extension and I want to add a 'Save as' button using Html/Javascript. Right now, users can only Right Click To 'Save as'. Since I am still new to Javascript, I have been struggling to find a way to do ...

Identifying geometric coordinates within Canvas

Currently, I am adding drag and drop functionality to my HTML5 Canvas application. I have encountered a challenge in determining how to detect if the shape being clicked on is not a rectangle or square. For instance, within my 'mousedown' event h ...

Is there a way to deliberately trigger an error using Selenium WebDriverIO?

Is there a way to trigger an error using ChromeDriver with Selenium WebDriverIO? I'm not sure if there's a method like browser.fire('error'). ...

The error message reads: "Attempting to call a class constructor Model without using the 'new' keyword in Sequelize 5 and Babel 7 results in a TypeError."

Currently working on a new project utilizing nodejs/express/sequelize. I'm using babel 7 to compile my ES6 code, and everything has been running smoothly with sequelize except for an issue that arises when attempting to use the removeHook method. When ...

Getting information from a database using PHP and AngularJS through the $http.get method

Currently, I am utilizing an AngularJS script to retrieve data from an external PHP file that is encoded in JSON within an HTML page. The method $http.get(page2.php) has been employed to fetch a JSON-encoded array located in another file. However, the issu ...

Guide on accessing the fastify application instance within an imported module

Currently, I am working on developing a rest API using Fastify and I am in the process of organizing my code into separate files for better structure. One issue I am facing is how to access the Fastify instance within a file that I import. The following s ...

Checking for multiple click events in jQuery

To access the complete code, visit the GitHub Pages link provided below: Link This is how the HTML code appears: <ul class="deck"> <li class="card"> <i class="fa fa-diamond"></i> </li> ...

Adding an image or icon inside a tooltip using ChakraUI or CSS in a React project

Looking to enhance my tooltip using the Chakra UI library by adding an image/icon directly into it. Instead of just displaying the label, I want the MdWarningAmber Icon to be visible within the tooltip itself, rather than next to the button that triggers t ...

The troubleshooting of debugging javascript remotely on IntelliJ with the JetBrains Chrome extension is proving to be unsuccessful

I've been attempting to set up a debugger for some JavaScript files that I'm working on in IntelliJ (version 2020.1.4). Following the guidelines provided here Debug with JetBrains Chrome extension, I believe I have successfully completed all the ...

The significance of Token Details in Tokbox

I'm currently working on developing a video chat platform that caters to various user roles - some may just observe while others actively participate in calls. I've been exploring the capabilities of the Tokbox Api () which allows metadata to be ...

Execution of Ajax call fails to occur synchronously

I have created a unique weather website that utilizes the flickr API as well as the yahoo API to gather weather data. However, I am facing an issue where the ajax call from the yahoo API does not retrieve the necessary data in time for the content of the p ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

A specific div remains in place as the user scrolls

Imagine a div that is positioned 60px from the top of the screen. What if, as you scroll down, it stops when it reaches 10px from the top and remains there for the rest of your scrolling session? And then, when you scroll back up, it goes back to its ori ...

Sending information into MySQL using NodeJS with the help of Postman

As a newcomer in the field, I am exploring how to combine MySQL with nodeJS for integrating projects into WordPress. app.post('/users/add', (req, res) => { id = req.body.id, firstname = req.body.firstname, surname = req.body.surname ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

Construct a drop-down menu using properties extracted from a JSON file in AngularJS

Is there a way to dynamically create a select element using attributes such as select id and select class from a JSON object defined in my controller, without knowing the specific attributes beforehand? Can this be achieved without resorting to dynamic pa ...

Is it possible to compare every element in an array with one another using an asynchronous process in NodeJS?

I am currently utilizing Resemble.js for image comparison within my web application. I have an array of image URLs that I need to compare with each other in order to calculate a unique score for each image. For example: [url1, url2, url3, url4] The minimu ...