Refreshing AJAX content with a dynamically adjusting time interval

I am facing a scenario where I have a webpage featuring a countdown alongside some dynamic data refreshed via AJAX. To optimize server load, I found a clever solution by adjusting the AJAX refresh interval based on the time remaining in the countdown, following guidance from

Specifically, to achieve a refresh rate of one minute when less than a day remains on the countdown and a rate of 5 minutes for over a day left, my implementation looks something like this:

var doStuff = function () {
    // Perform actions
    var remainingTime = JSONData.restTime;

    if(remainingTime > one day) {
        setTimeout(doStuff, 300000);
    } else {
        setTimeout(doStuff, 60000);
    }
};

setTimeout(doStuff, 60000);

The "remainingTime" variable is derived from the JSON utilized for refreshing the content. Although it functions properly, I am seeking an enhancement. The initial AJAX call currently occurs after one minute of loading the page (as per the last "SetTimeout" in the code). Ideally, I aim to align this initial call with the remaining time—having it execute after 5 minutes if more than a day is left and after 1 minute for less than a day.

How can I synchronize the first AJAX call with the remaining time?

Answer №1

Is it possible to just call doStuff instead of initially using setTimeout?

var doStuff = function () {
  // Do stuff
  var remainingTime=JSONData.restTime;
  if(remainingTime>one day) {
    setTimeout(doStuff, 300000);
  } else {
    setTimeout(doStuff, 60000);
  }
};

doStuff();

If JSONData isn't loaded yet, consider calling doStuff from the first AJAX success callback.

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 Ajax PHP function only works on the initial call

The function below calls a PHP file that returns results in JSON format, which are assigned to JavaScript values. The PHP function has been thoroughly tested and works as expected. The results are stored in variables until the market variable is changed wi ...

What are the steps to rectify the issue of displaying data accurately on

I am working on my ReactJS project and using devextreme to create a unique circular gauge. However, I'm facing an issue where certain values are not being displayed correctly. For instance, instead of showing the value 5011480286.78, it is displaying ...

Enhance autocomplete functionality by adding an additional parameter specific to Zend Framework

My form includes two fields: country club The club field is generated using the ZendX_JQuery_Form_Element_AutoComplete Element, which also creates this javascript code: $("#club").autocomplete({"url":"\/mywebsite\/\/mycontroller\/au ...

Running a server-side function on the client-side in Node.js

I am currently working with the following code snippet on the server: var game = io.listen(app); game.sockets.on('connection', function(socket){ storePlayers(socket.id); //Only the player who connects receives this message socket.em ...

Interaction issue with Material UI and React tabs: hovering fails to open and close tabs correctly

I am currently immersed in a project that involves React and Material UI. My goal is to create tabs that trigger a menu upon hovering, but I seem to be facing some challenges with this functionality. That's why I'm reaching out here for assistanc ...

Upgrading an Express 2.x application to Express 3.0

I am currently studying NodeJs and Express and am in the process of converting a tutorial app from Express 2.5.9 to version 3.0. The following code is now causing an error "500 Error: Failed to lookup view "views/login". How can I update this to render cor ...

I require displaying the initial three letters of the term "basketball" and then adding dots

Just starting out with CSS and struggling with the flex property. Seems to work fine at larger sizes, but when I reduce the screen size to 320px, I run into issues... Can anyone help me display only the first three letters of "basketball ...

Transforming Arrays of Objects into a Single Object (Using ES6 Syntax)

My attempt to create aesthetically pleasing Objects of arrays resulted in something unexpected. { "label": [ "Instagram" ], "value": [ "@username" ] } How can I transform it into the d ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...

Using async/await with Axios to send data in Vue.js results in different data being sent compared to using Postman

I am encountering an issue while trying to create data using Vue.js. The backend seems unable to read the data properly and just sends "undefined" to the database. However, when I try to create data using Postman, the backend is able to read the data witho ...

How to effectively manage time and regularly execute queries every second using Node.js?

Currently working on developing a web software using node js with an Mssql database. There is a table in the database that includes a datetime value and a bit value. The bit value remains at 0 until the real-time matches the datetime value, at which point ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Looking to pass two distinct variables using a single props with v-if in Vue-JS. Any suggestions?

I am attempting to pass different data to my other component. Essentially, when my variable firstvalue is not null, I want to send firstvalue. Currently, this setup is functioning as expected. However, I now wish to send secondvalue if it is not null. < ...

There seems to be an issue with the file upload process

I'm attempting to upload an image using the following code: $sourcePath = $_FILES['file']['tmp_name']; $targetPath = "upload/".$_FILES['file']['name']; move_uploaded_file($sourcePath, $targetPath); However, I ...

Ways to identify if there is a problem with the Firestore connection

Can anyone help me understand how I can use angularfire2 to check the accessibility of the cloud firestore database and retrieve collection values? If accessing the cloud database fails, I want to be able to retrieve local data instead. This is an exampl ...

Updating charts in React using Chart.js with the click of a button

I am currently learning React and Chart JS, but I have encountered an issue. I am unable to change the data by clicking on a button. Initially, the graph displays: var Datas = [65, 59, 80, 81, 56, 55, 69]; However, I want to update this graph by simply p ...

What is the best way to extract a list of particular items from a nested array?

When I execute the following code: var url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=categories&titles=Victory_Tests&callback=?"; $.getJSON(url,function(data){ $.each(data, function(i, item) { console.lo ...

What happens to the npm package if I transfer ownership of a github repository to a different user?

I was considering transferring a GitHub repository to another user or organization, but I have concerns about what will happen to older versions of the npm package associated with it. Let's say my Node.js package is named node-awesome-package. Versi ...

Alter the Default Visibility on an HTML Page from Visible to Hidden with JavaScript

I found this code snippet on a website and made some modifications. On my webpage, I have implemented links that toggle the visibility of hidden text. The functionality is working fine, but the issue is that the hidden text is initially visible when the p ...