The persistent problem with constantly polling the $.ajax request

One issue I'm facing involves a continuous polling $.ajax request. The challenge lies in initiating it immediately first, and then running it at intervals set in the setTimeout call.

Take a look at the example code here.

myObj = {};

var output = '';
var items = '';
myObj.displayItems = function() {
console.log('displayItems executed');
output = '';
$.each(items, function(index, val) {
 output += '<li>' + val.player.firstName + ' ' + val.player.lastName + '</li>';
});
$('#content').html(output);

};

$(document).ready(function() {
(function loadData() {
setTimeout(function() {
console.log('loadData executed....');
return $.ajax({
url: '//jsbin.com/xinixa/1.json',
type: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
items = data.apiResults[0].league.season.draft.rounds[0].picks;
loadData();
myObj.displayItems();
},
});
}, 3000);
})();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="content"></div>
</body>
</html>

Every time I try to put the setTimeout call inside the function during refactoring, I encounter errors. Making the function non-self-executing also leads to errors.

Answer №1

It's unclear if the term "refactor" is being used in the same way I interpret it, but reorganizing your code can greatly assist in identifying the issue. Excessively nested functions like the ones you have can be unnecessary and often lead to confusion. Here's a simple refactor to eliminate nesting. While it may not achieve your intended outcome, it does run smoothly without any errors. DEMO:

var myObj = {};
var output = '';
var items = '';

myObj.displayItems = function() {
  console.log('displayItems ran');
  output = '';
  $.each(items, function(index, val) {
    output += '<li>' + val.player.firstName + ' ' + val.player.lastName + '</li>';
  });
  $('#content').html(output);

};

var loadData = function() {
  setTimeout(makeAjaxRequest, 3000);
};

var makeAjaxRequest = function() {
  console.log('makeAjaxRequest running');
  return    $.ajax({
    url: '//jsbin.com/xinixa/1.json',
    type: 'GET',
    dataType: 'json',
    cache: false,
    success: successHandler,
  });
};

var successHandler = function(data) {
  items = data.apiResults[0].league.season.draft.rounds[0].picks;
  loadData();
  myObj.displayItems();
};

$(document).ready(loadData);

Here are a few more suggestions for improvement:

  • Eliminate the globally-saved variables output and items. output could be integrated as a state within the myObj object, and items should be passed as a parameter to your displayItems() function.

  • Consider renaming myObj for clarity.

  • Considering using setInterval instead of setTimeout if you want a function to repeat every 3 seconds.

Answer №2

If my understanding is correct, this solution should work for your needs. You can view it here

myData = {};

var output = '';
var items = '';
myData.displayItems = function () {
    console.log('displayItems executed');
    output = '';
    $.each(items, function (index, val) {
        output += '<li>' + val.player.firstName + ' ' + val.player.lastName + '</li>';
    });
    $('#content').html(output);
};

$(document).ready(function () {
    (function loadData() {
        console.log('loadData initiated....');
        $.ajax({
            url: '//jsbin.com/xinixa/1.json',
            type: 'GET',
            dataType: 'json',
            cache: false,
            success: function (data) {
                items = data.apiResults[0].league.season.draft.rounds[0].picks;
                myData.displayItems();
                setTimeout(loadData, 10000);
            },
        });
    })();
});

The only modification I made was in the loadData function. The method still immediately invokes, but I placed the window.setTimeout() within the success callback (I changed the timeout to 10 seconds for testing). This schedules the timeout after the previous successful callback, effectively creating a polling mechanism.

If you monitor the console, you will observe that loadData() runs instantly, and each subsequent call occurs 10 seconds after the prior one.

I hope this explanation clarifies things for you. Do let me know if there's anything else I can assist you with.

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 process of a ReactJS component's lifecycle is affected when an onClick event triggers a fetch function, causing the state

For the past week, I've been grappling with a coding challenge. My goal is to create a basic Pokedex featuring the original 151 Pokemon. The list of Pokemon should be displayed on the right side of the screen, pulled directly from a .json file copied ...

Obtaining template attributes in CKEditor: A guide

I have been working with the template plugin in CKEditor to load predefined templates. Each template is defined as follows: templates: [ { title: "Quickclick 1", image: "template1.png", description: "Quickclick 1 template", html_et: "& ...

What is the best way to pass information between Express middleware and endpoints?

Many middleware packages come with factories that accept an options object, which often includes a function to provide necessary information to the middleware. One example of this is express-preconditions: app.use(preconditions({ stateAsync: async (re ...

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...

Error: Unable to cast value "undefined" to an ObjectId for the "_id" field in the "User" model

Whenever a user logs into their account, I am trying to retrieve their data on the login screen. The login functionality itself works perfectly, but unfortunately, the user data is not displaying. I have tried troubleshooting this issue by making changes i ...

SmartEdit functions properly when spartacus is running using yarn start --ssl, but does not work without SSL enabled

I followed the smartedit setup instructions at and everything works well when I start the Spartacus server with yarn start --ssl. However, if I start the server with just yarn start, the storefront does not appear. See image here for reference ...

What is preventing me from installing react-router-transition on the 1.4.0 version?

$ npm install -S <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dffe8eceef9a0ffe2f8f9e8ffa0f9ffece3fee4f9e4e2e3cdbca3b9a3bd">[email protected]</a> npm ERROR! code ERESOLVE npm ERROR! Unable to r ...

How can I improve my usage of jQuery in assigning the enter key to submit an ajax form?

My HTML code: <form action="/comment_replies/ajax_create/30?type=2" id="new_comment_2_30" method="post" onsubmit="new Ajax.Request('/comment_replies/ajax_create/30?type=2', {asynchronous:true, eva ...

Mist Conceals Celestial View (THREE.JS R76)

I have a cylindrical camera setup with fog to hide the end of the tube. However, I am trying to make the skybox visible through the alpha map sides of the cylinder. The current issue is that the fog is blocking the visibility and I'm looking for a sol ...

HTML table row content should be aligned to the left side

I am attempting to align the data in the 'Address' column without any margin. I want it to start from the left since it's overflowing. You can find the HTML, CSS, and JS code here Even though I tried using <td align="left">..</td& ...

Loading custom places in ArcGIS from a file or database

Hey there, I was wondering about loading custom places with Arcgis similar to Google maps loading from a .xml file. I noticed that Arcgis uses examples saved in .json format, but when I tried putting the example .json on my local server it wouldn't lo ...

I have to ensure that a plugin is only loaded once its dependency has been loaded with RequireJS

Currently, I am utilizing the jquery.validationEngine.js plugin and facing an issue. It seems that jqueryValidateEnglish is unable to function properly unless jqueryValidateEngine is loaded beforehand. In my code for jquery.wrapped.validationEnglish2.js, ...

retrieve a static method that returns an asynchronous value

Is there a way to have a static ES6 method in my code that simply returns a value instead of a promise? I'm looking for a solution to this problem: export default class Member { static existingMember() { var _existingMember; // DB.findExist ...

Adjust the height of a div in JQuery to fit new content after specifying a height previously

I have a division element with an initial height of 0 and opacity set to zero, its overflow is hidden, and it contains some content. <div style='height: 0px; opacity: 0px; display: none; overflow: hidden; border: 1px solid #000;' id='myd ...

Issues with the functionality of the jQuery notify plugin are being encountered when used in a

I am currently utilizing the jQuery notify plugin and have included all the necessary JS files in the header. However, whenever I attempt to call the $.notify function in another JS file that also involves AJAX, I encounter difficulty accessing the $.notif ...

How can I style the inner div by adding a class to the first div?

In my project, I have a list of elements that are generated dynamically, all styled the same way but with different content. The first element has a specific styling, and if it doesn't render, I want the second element to inherit that styling. < ...

Retrieve the element (node) responsible for initiating the event

Is there a way to identify which element triggered the event currently being handled? In the following code snippet, event.target is only returning the innermost child node of #xScrollPane, with both event.currentTarget and event.fromElement being null. A ...

Checking for Internet Connectivity in Mobile HTML5

Is it possible to check for internet connectivity on a mobile device? Can websockets be utilized to ping a server and determine if the connection is available? I am feeling frustrated as I believed there was a ping function in websockets for client-side u ...

Encountering difficulty in reading a session variable when accessing it through Ajax, however, the variable is successfully retrievable when called from the controller in ASP.Net

I have implemented a method within the controller to retrieve the value of a session variable. However, when I attempt to call this method from Ajax jQuery, I am unable to obtain the value. Interestingly, if I try to read the session value from another met ...

A method parameter in an MVC controller can be bound to HTML form properties by following these steps

Struggling to bind a controller post method to a basic HTML form on the view. Trying to understand how to populate the parameter and call the method using form data. Controller method: [HttpPost("addcomment")] public JsonResult AddCommen ...