Continuously looping in Firefox on Android is the setInterval function

I have a brief section of JavaScript that I would like to use to check a server every few seconds and update the DOM.

function updateCard() {    
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            card = JSON.parse(this.responseText);
            document.getElementById("season").innerHTML = card.season;
        }                  
    };                     
    xhttp.open("GET", "/curr_card/", true);
    xhttp.send();
}
window.onload = updateCard;
window.setInterval(updateCard,2000);

In most browsers, this is what occurs. There are occasional calls to updateCard, but generally speaking the server displays around half a connection per second per client.

However, when viewing the page in Firefox on Android (49.0), the browser suddenly starts polling /curr_card/ repeatedly, many times per second.

Some people have suggested replacing the setInterval line with

window.setInterval(function() {updateCard();},2000);
, but this does not solve the issue.

As a newcomer to JavaScript and AJAX, I am unsure why this is happening. Is it a bug in Firefox? I can provide more code upon request.

Thank you in advance.

Answer №1

Following thorough testing and analysis in the original poster's comments, it was determined that this particular issue is unique to Firefox on the OP's HTC M7 device, as it was not able to be replicated on a Galaxy S7 running the same version of Firefox.

Answer №2

It's possible for this issue to occur not just with Firefox on certain devices.

The problem may arise when the response has not completed due to a delay in server response, leading to multiple requests being sent one after another.

One solution could be:

function updateCard(before, after) {    
    if(before) {
      before();
    }

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            card = JSON.parse(this.responseText);
            document.getElementById("season").innerHTML = card.season;
        }

        if(after) {
          after();
        }
    };                     
    xhttp.open("GET", "/curr_card/", true);
    xhttp.send();
}

window.onload = updateCard;

var updateCardRunning = false;
setInterval(function() {
  if(updateCardRunning === true) {
    console.log('postponing to next schedule');
    return;
  }

  updateCard(
    function() {updateCardRunning = true;},
    function() {updateCardRunning = false;}
  );
}, 2000);

or:

 function updateCard() {    
    var xhttp = new XMLHttpRequest();
    window.xhttp = xhttp;

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            card = JSON.parse(this.responseText);
            document.getElementById("season").innerHTML = card.season;
        }
    };

    xhttp.open("GET", "/curr_card/", true);
    xhttp.send();
}

window.onload = updateCard;
setInterval(function() {
  if(window.xhttp) {
    window.xhttp.abort();
  }
  updateCard();
}, 2000);

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

Returning a 404 Error stating "Invalid request to /api/users/register."

Encountering an issue with proxy connection - unable to determine the root cause despite verifying all routes. Not able to successfully register the user and store data in MongoDB. Seeking suggestions for resolution. Thank you. Attempting to send user reg ...

Troubleshooting JavaScript If-Else Statements

Having a bit of trouble with my if else structure. When I enter the correct star name like "Vega", it incorrectly shows me "Error" instead of the expected result "Lyra". Here's my code snippet: var stars = ["Polaris", "Aldebaran", "Deneb", ...

Ways to conceal or deactivate button controls on videojs?

I am building an application using video.js and Vue. I am looking for a way to hide or disable certain controls like the play button, playback rate, and make the progress bar read-only. In the video.js documentation, I found that using controls: false hi ...

the term 'this' does not pertain to the user object within the mongoose model

Here is a snippet of my code that saves a user object to a database using Express: api.post('/signup', function (req, res) { var user = new User(); user.name = req.body.name; user.email = req.body.email; user.setPassword(req.body ...

The utilization of CakePHP buttons for submitting forms, along with the seamless integration of

<?php echo $this->Form->button('A Button'); echo $this->Form->button('Another Button', array('type'=>'button')); echo $this->Form->button('Reset the Form', array('type'=> ...

I'm attempting to showcase an HTML file by using res.sendFile within the Express framework

As part of my workflow implementation, I have set up a scenario where upon user login, the credentials are sent via Ajax to an Express route for verification. If the user exists, the route responds with a message "authorised" triggering a second Ajax call ...

Is it possible to have unique color tags in Material UI Autocomplete?

I'm currently diving into the world of material-ui and encountering some challenges that I could use help with. I am trying to incorporate multiple arrays into the autocomplete menu (e.g., options={top100Films, top100Shows}, but with the correct sy ...

Using Javascript to parse a regular expression in a string

I am facing a challenge with a JavaScript string that contains contact information that needs to be filtered. For example, I want to mask any email or phone number in the message. I have attempted the following approach: function(filterMessage) { ...

What is the best way to display a child component inside an iframe using Vue.js?

Looking to provide a live preview of an email before sending it out, I've opted to use an iframe to contain the preview and prevent style leaks. The goal is for the preview to update dynamically as the user fills out form details. How can I display a ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Angular and AngularJS directives work together to indicate events on a line chart

Currently, I am creating a dashboard using AngularJS along with Angularjs-nvd3-directives, mainly focusing on line charts. I am interested in adding markers to the chart for specific events. For instance, if I have a time series data, I want to be able to ...

Troubleshooting unexpected behavior with Custom Guest middleware in Nuxt Project

I have implemented the Nuxt auth module for my project. To manage the login page, I created a custom middleware called guest.js, which has the following code: export default function ({ $auth, store, redirect }) { if (!process.server) { if ($auth ...

Encountering Problems with Dependencies in Selenium Webdriver 2.20 for .Net Client?

Currently facing a strange issue as I begin working on some acceptance tests and tried to NUGet the latest Selenium Webdriver. Installation went smoothly, and I quickly wrote a test to ensure everything was functioning: [Test] public void should_navigate_ ...

Unable to access specific data from the JSON string retrieved from the backend, as it is returning a value of undefined

After receiving a JSON string from the backend, my frontend is encountering issues when trying to index it post using JSON.parse(). The indexed value keeps returning as undefined, even though it's a JSON object literal and not within an array. For th ...

InnerHTML syntax for creating the button in the cell is not functioning properly with the HTML onclick event

I'm facing an issue with my code where I am trying to insert a button into a table cell. The button has an action assigned to it using the onclick attribute. However, no matter how I try to use single quotes with or without backslashes in the syntax o ...

Creating an HTML5 input field with the type "datetime-local" that works seamlessly in Firefox

Currently, I am incorporating HTML5 date and time input fields within an AngularJS-based interface: <input type="datetime-local" ng-model="event.date_time.start" /> <input type="week" ng-model="event.date_time.start" /> However, my goal is to ...

Running AngularJS controllers should only occur once the initialization process has been fully completed

I am facing a situation where I need to load some essential global data before any controller is triggered in my AngularJS application. This essentially means resolving dependencies on a global level within AngularJS. As an example, let's consider a ...

Transformation of JSON data from Array to Object

I have a JSON data structure that looks like this: { tag: 'new-tag', stream_subjects: [1, 2, 3] } My goal is to transform it into the following format: { tag: 'new-tag', stream_subjects: [ {subject_id: 1}, {subject_id ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

Using Jquery to send data with Ajax through a POST request to an endpoint

I'm having trouble sending data to an endpoint. The documentation specifies using a syntax like product[xx][amount] where xx is an id, but I can't seem to get it right. var postData = { product:153, amount:1 }; ...