Prevent the execution of a Javascript function if it is already in progress

I've developed a function that retrieves records from a third party, and this function runs every 10 seconds. However, as I debug through Firefox, I notice a long queue of ajax requests. I'm contemplating including a statement that can signal to the next request about ongoing ajax executions. Since the function and its purpose remain the same with each execution, it seems redundant to trigger another one if the previous one is still processing. Here's what I've attempted:

function checkExecution(){
    if(sessionStorage.do == true){
        $.ajax(function(){
            continue...
        });
    }

    sessionStorage.do = true;
    sessionStorage.do = false;
}

setInterval(checkExecution, 10000);

Unfortunately, the above approach is not working as intended. Could someone offer guidance on how to achieve this? I would greatly appreciate it.

Answer №1

Make sure to verify if the ajax request has been completed before initiating the next one. See the code snippet below for an illustration:

var ajax_in_progress = false;
function processSomething() {
    if(!ajax_in_progress){
    ajax_in_progress = true;
        $.ajax(function(){
            success : function(data) {
                    ajax_in_progress = false;
                },
                error : function(data, textStatus, errorThrown) {
                    ajax_in_progress = false;
                }
        });
     }
  }

setInterval(processSomething, 10000);

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 preventing the items inside the <ul> element from displaying?

Struggling to grasp pagination, I can't figure out why the contents of "li" under the "ul" disappear while the "ul" container continues to display despite specifying in the JavaScript that only 6 should be visible on the page. The "ul" and "li" elemen ...

Tips for maintaining DataTables filters after navigating Back/Forward or refreshing the page

We are currently utilizing DataTables for our table, and we are encountering difficulties in retaining the history of filters that were previously applied to the table. This would allow users to navigate back and forth and refresh through these filters. O ...

Using NextJS to Load Fonts from a Database

I've implemented a feature in my NextJS and Tailwind CSS app that allows users to select a theme with different color schemes and font options. The fonts available are all from Google Fonts. However, I'm facing an issue with loading the selected ...

Pause a YouTube video automatically when the window is not in focus using FancyBox

I have successfully implemented dynamic play/pause functionality for a YouTube video, as demonstrated in my weave. However, I am facing challenges in making it work dynamically with FancyBox using the onBlur event (to pause the video when the window is no ...

How can I load only specific images on a webpage using HTML?

I attempted to implement an image filter for my website by using the code below: <script> function myFunction() { // Initialize variables var input, filter, ul, li, a, i; input = document.getElementById('myInput'); filter = input.value.toU ...

Developing a Link Element in Angular 2

Exploring the creation of a wrapper component in Angular 2, inspired by tools like react-bootstrap. The goal is to avoid repeating the component structure each time and instead create a reusable component. The desired reusable component should have a stru ...

I'm having trouble understanding why I can't redirect to my GET router after making a POST request

profile.ejs <body> <div id="box"> <h1>Greetings, <span><%= user.name %></span>!<hr> How are you feeling today?</h1> <!-- <form action="/users/logout" method=" ...

Using JQuery in AJAX, you can easily upload numerous images and then handle them using PHP

I need help with something new to me - how can I achieve this using ajax? I know how to do it with plain html multiform parts, but not with ajax. Here is the pseudo code I currently have: HTML: <input type="text" class="imgform" name="imagename" valu ...

Supplier for a module relying on data received from the server

My current component relies on "MAT_DATE_FORMATS", but I am encountering an issue where the "useValue" needs to be retrieved from the server. Is there a way to make the provider asynchronous in this case? export const MY_FORMATS = { parse: { d ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...

Displaying dropdown options based on the previous selection made by the user

Can I link the data in my second dropdown to the selection made in the first dropdown? I tried a similar solution from stackoverflow without success. You can find the reference here. The code works when directly copied and pasted but not within my system. ...

In an empty JavaScript MVVM Organization View, the ViewModel is packed with lines of code

I find myself always placing all of my code within the ViewModel because nothing else seems to fit. What kinds of things should be included in the view? Does anyone have any examples? ...

Using Vue 3 to send formdata with axios

I've been attempting to upload images to a backend expressjs API using Vue 3. I'm creating a FormData object named "files" and sending it via axios to the server. However, the server isn't receiving anything (req.files is undefined). The ser ...

obtain information from a Java servlet on a web page

I am working on a webpage that displays various coordinates (longitude, latitude), and I need to create a Java class to sort these coordinates. My plan is to send the coordinates to a Java servlet before displaying them on the webpage. The servlet will th ...

How come eslint is unable to detect all files within a directory, yet it can detect a single file?

Here is the organization of my files and directories. https://i.stack.imgur.com/YWNw3.png I am looking to set up some eslint rules for my code detection. In my .eslintrc file, I have included these configuration settings. { "extends": "airbnb", "ru ...

Is it possible that when a user is redirected to a different URL, Chrome terminates any pending Ajax requests?

Currently, I have a function that allows the user to unlock a list they are currently editing: function cancelLock(id) { $.ajax({ type: "POST", url: "/ajax.php?action=cancelLock", dataType: 'json', data: "id="+ id }); retur ...

If the div is devoid of content, then remove the class

<div class="slider">content goes here</div> <div id="slider-2" class="active inactive">also some content here</div> <script type="text/javascript"> function checkEmpty( element ){ return !$.trim(element.html()) ...

React hooks - Issue with updating state properties within sidebar display

When resizing the window, I have an event that will display either the desktop sidebar or the mobile sidebar. However, there are variables that are not immediately updated to show the sidebar correctly based on the window size. In a desktop window, this ca ...

What is the best method for developing a draggable element that remains stable?

I have developed a simple script for draggable elements, however, I am facing an issue. Whenever I move the mouse quickly, the element loses focus. Is there a way to improve the stability of the dragging functionality regardless of how fast I move the mou ...

Is there a minimum height restriction for v-select in Vuetify.js?

Looking at the code snippet provided below, I am facing an issue while trying to decrease the height of a v-select element. It seems like there is a minimum limit set for the height, as reducing it beyond height = 40 doesn't have any effect. Is there ...