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

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

Display array information within a table using ajax

Currently working with the Zend Framework to develop a website. I have an array called $shadow which contains IDs of individuals. The query for $shadow runs smoothly in the Model and gets called in the Controller without any issues. However, now I need t ...

Failure to append an object to the array occurs when submitting an HTML form

I am facing an issue with a form that is supposed to add input values to an array as objects when submitted. However, every time I submit the form, the console briefly shows that there is an array with one object, only for it to disappear. Below is the f ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

Strange state manipulation in React JS using MaterialUI

Having trouble displaying an input component from material-ui, as it crashes the page when I type a few letters. import React from 'react'; import Input from '@material-ui/core/Input'; export default function ComposedTextField() { ...

an unsuccessful attempt to retrieve data was made

After using the fetch function to retrieve a list of notes, nothing appears when I console.log it. I have double-checked the URL and it is correct. Here is the code snippet: import React, { useState, useEffect } from 'react' const NotesListPage ...

JavaScript's Selenium WebDriver - Explicit Waiting

Currently, I am utilizing selenium-webdriverjs. My objective is to pause until a specific element is displayed. To accomplish this, I have implemented an explicit wait that operates effectively: var shown = false; driver.wait(function(){ driver.findEl ...

Using Formik inside Material-UI's table components

My goal is to design a material UI table where each cell acts as a Formik input. However, I've encountered errors with Material UI when attempting to use a Formik Object within TableBody or TableItem tags. Here's an example image of what I' ...

Swap out the %20, which signifies a space in the iron router context

I am attempting to substitute the %20, which signifies a space in the URL, with a different character. Router.map(function () { this.route('promos', { path: '/:promo_name', waitOn: function(){ return Meteor.subscribe( ...

Is there a way to retrieve and gather all data from various scopes and then access them collectively?

I attempted to scrape information from a website using Node.JS + Cheerio + Axios. I was able to retrieve all the necessary data, but encountered an issue with returning the data from different scopes in order to receive it. Currently, I can only obtain the ...

Tips for declaring a non-reactive instance property in Vue.js with TypeScript

I am currently in the process of transitioning my Vue.js components to TypeScript. In accordance with the recommendations provided in the documentation, I attempted to utilize Vue.extend() for my component implementation. The code snippet for my component ...

Performing a Jquery Ajax get request on multiple URLs within a single function

In my current setup, I have a form with a select dropdown and three submit buttons labeled as "Daily new likes", "Daily unlikes" and "Daily page views". The form includes an Ajax call within the submitForm function that sends the selected option value to a ...

The redirection did not occur as no authorization token was detected

I have two Nodejs applications, one for the front-end and the other for the back-end. The back-end app is secured with token access using express-jwt and jsonwebtoken middlewares. My issue is as follows: when I make a request from the front-end to the bac ...

Wordpress problem with Bootstrap JavaScript code involving data-toggle="collapse"

Currently facing an issue with my project. This is my first attempt at creating a WordPress blog, inspired by the HTML site www.humantools.com.mx and building a blog for it at www.humantools.com.mx/blog. There's a strange problem: when logged in, the ...

Definition for TypeScript for an individual JavaScript document

I am currently attempting to integrate an Ionic2 app within a Movilizer HTML5 view. To facilitate communication between the Movilizer container client and the Ionic2 app, it is crucial to incorporate a plugins/Movilizer.js file. The functionality of this f ...

Issue with HTML 5 audio player not functioning correctly in Chrome browsers when trying to forward or rewind playback

I am encountering an issue with running the HTML5 audio player in Chrome. It works perfectly fine in IE 9+ and Firefox. I have implemented JavaScript functions for forwarding and rewinding the audio player on F7 and F8 key press. These functions work seaml ...

Error: The hyperlink in the response from the Ajax request is not functioning as expected

I've exhausted all the suggestions for fixing this issue, but nothing has worked so far. Currently, my setup involves making an AJAX call to a PHP page called livesearch.php from the index page in order to retrieve live search results. <html> ...

What is the process for attaching an on-click event listener by utilizing an argument that is passed to a function in JavaScript?

These are the functions I have created: function type(message) { document.getElementById("body").innerHTML="<div id=\"textbox\" class=\"textbox\"></div><div id=\"oc\&q ...

What is the best way to display a popup window on top of the parent window?

How can I display a popup window on top of the parent window when a button is clicked? I have tried using the Window.Focus() method, but the popup window keeps going back behind the parent window. I would greatly appreciate any help on this. Thank you in ...

Ways to verify if the current user has blocked the target user using Acts-as-Follower

I am having trouble verifying if the current user has blocked the target user. My goal is to implement a toggle button for the block/unblock feature. It seems like other solutions may not be compatible with AJAX functionality. How can I determine if the cu ...