The asynchronous nature of how setInterval operates

I am working with a setInterval function that executes asynchronous code to make calls to the server:

setInterval(()=> {
    //run AJAX function here
}, 5000);

In scenarios where the server does not receive a response within 5 seconds, there is a likelihood that setInterval will run again and initiate multiple requests on the same endpoint. Is there a way to ensure that the next execution of setInterval only starts after the AJAX function successfully returns a response?

Answer №1

If you're looking to implement a delay in your AJAX requests, using setTimeout is the way to go.

Here's some pseudo code to help you out:

const doAjaxWithDelay = (delay)=>{
      setTimeout(()=>{
        $.ajax({
        ...
        }).done(()=>{
          // Add your custom logic here
          doAjaxWithDelay(5000)
        })
      }, delay)
    }
    doAjaxWithDelay(0);

Answer №2

Opt for setTimeout in place of other methods

function runTimer = () => {
  setTimeout(()=> {
    //execute AJAX function in this block
    ajaxFunction();
  }, 5000);

function ajaxFunction() {
  //perform actions in case of success
    //handle success situation
  // perform actions in case of failure
    // handle failure situation
  // final actions to be executed
    runTimer();
}

runTimer()

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

When using Thunderbird Webextensions, calling .messages.getFull() may result in the Exception 0x80004005 being raised, specifically indicating

This question is a follow-up to a previous question/answer found at: In this scenario, the code attempts to retrieve a list of accounts, select the emailAccountName, get a MessageList object from the specified wantedMailFolderType, and then access a Messa ...

Use jQuery to switch back and forth between the login and registration forms on a single

I've set up two forms, one for login and one for registration, with the default view showing the login form. There's a link that says "Don't have an account?" and when it's clicked, the registration form will display while the login for ...

Adding additional `select` dynamically causes the value to disappear from view

After attempting to replicate the functionality of the select field, I encountered an issue where it no longer displays any values. Specifically, if I opt for a small size, I encounter this error message in the console. https://i.stack.imgur.com/5hKX6.png ...

How can I use jQuery to set the color of every other row in a

I'm facing an issue where I want to use jQuery to set the color of alternate rows in an HTML table. However, every time I add a new row, the color of the entire table switches. Below is the JavaScript code snippet that I am utilizing: var alternate = ...

Retrieving component layout from file

Storing the component template within inline HTML doesn't seem very sustainable to me. I prefer to load it from an external file instead. After doing some research, it appears that utilizing DOMParser() to parse the HTML file and then incorporating th ...

Searching for form fields in Wordpress using custom post types

Currently, we have a dropdown option that automatically populates from custom post types and displays for the customer to choose from. However, the list has become extremely long, so they would like the functionality of being able to start typing a company ...

Exploring the contrast between router.pathname and router.route within Next.js

Essentially, my goal is to utilize the NextJS router to access the page url by doing the following: import { useRouter } from "next/router"; const SomeComp = props => { const router = useRouter(); } Yet, when I console.log() the propertie ...

Accessing an array of objects within nested objects results in an undefined value

I am facing an issue with my JavaScript object that is retrieved from MySQL. The object has a property which contains an array of other objects, as demonstrated below: parentObject = { ID: "1", Desc: "A description", chi ...

Calculating the total sum in Vuejs when an event is triggered

I am faced with a situation where the price of a product is added to an existing total when a user increases the quantity. However, the problem lies in the fact that even if the user decreases the quantity, the price continues to increase. Solution html ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

Tips for utilizing jQuery Ajax data action

I've been trying to understand how to effectively utilize the data parameter in a $.Ajax call. However, I am facing confusion regarding the 'action' part within the data call. Is it meant to trigger an action in a controller? If so, how can ...

What is the best way to manage returning to the original page that was loaded when utilizing the History API?

I'm in a bit of a pickle here. I've been using History.js with the History API and everything was going smoothly until I encountered an issue. Let's start with a simple page setup like this: <div ="header"> Header </div> <d ...

Switch between various API content upon clicking (JavaScript)

Upon receiving data from an API in JSON format using PHP, I aim to incorporate a filter mechanism for displaying distinct content sourced from the API. For instance, by specifying a filter in my API call, I can retrieve separate datasets such as one with ...

Encoding large files using the Base64 format

Is there a method to encode a file of, say, 2 gigabytes without splitting it into chunks? I am encountering errors when trying to handle files larger than 2GB due to their size being too large for the filesystem. Breaking the file into smaller chunks is ...

data retrieval not refreshing sorting post construction

My challenge involves fetching data from MongoDB with sorting. While it works perfectly on the development server, it fails to update the data after being built and hosted. import Review from "@/models/review"; import connectdb from "@/util/ ...

Is there a period, question mark, apostrophe, or space in the input string?

Currently, I am in the process of developing a program that can determine if an input string includes a period, question mark, colon, or space. If these punctuation marks are not present, the program will return "false". However, if any of them are found, ...

Issues may arise in TypeScript when you are working with an array of objects along with other properties within a type

I am encountering an issue with an object structure similar to the one below: let Obj = { ['0'] : { mode: 'x' }, getMode: () => 'x' } The problem arises when I attempt to create a type definition as shown here: type Obj = ...

Encountered an error while loading resource: server returned a 500 status (Internal Server Error) - A NodeJs Express and MongoDB Web Application hit a snag

I am currently in the process of developing a web application using NodeJS Express and MongoDB. However, I have encountered an issue while attempting to implement AJAX functionality to load and display comments on the post page. The "post-detail" page is ...

Sending JSON data stored in a JavaScript variable through a jQuery POST request

I am currently attempting to retrieve data from a remote location using a JQuery post method. It works perfectly fine when I directly input the data to be posted, but for some reason, it fails when I store the JSON in a JavaScript variable and pass it in. ...

AngularJS factory architecture for multiple functions

It's not the exact data I'm using in my project, but I'm simplifying it for demonstration purposes. In my AngularJS app, I have a factory like this: myApp.factory('inputinfo', function () { var self = { test: function (in) { ...