0

I have a react app which updates data from a database on a 2 second timer:

componentDidMount() {
    this.interval = setInterval(()=> this.getSelPos(), 2000);
  }
  
  componentWillUnmount() {
    clearInterval(this.interval)  
  }
  
  async getSelPos() {
      const response = await axios.get("http://localhost:5000/selector",  { crossdomain: true });
      console.log(response.data);
      this.setState({SelectorPos: parseInt(response.data.selector)});
      this.setState({Pressure: parseInt(response.data.pressure)});
      this.setState({Temperature: parseInt(response.data.temperature)});

This just sends to a node api that gets a value from my database and responds. Currently set to poll every 2 seconds and update the page.

The problem I'm running into is that when I tab out or minimise the browser for a few minutes it'll hang for a few seconds on returning, or it'll crash entirely. I suspect this is due to the browser being smart and freezing the tab when not in use. But I'm stumped as to how to fix this issue?

Cm1602
  • 91
  • 11
  • `Currently set to poll every 2 seconds `...that's way too frequent and is likely the source of your problem - JS may pause while the tab is not visible, and then will try to catch up. You also run the risk of overloading your server with concurrent requests, especially if many users are on this page at once. If any requests are slow for any reason, you risk making the problem worse because the requests will start to overlap. – ADyson Oct 14 '21 at 08:42
  • yes you are right, browsers do that to save memory and battery. try using web workers as mentioned: https://stackoverflow.com/questions/34165421/javascript-setinterval-and-minimized-windows – boxdox Oct 14 '21 at 08:42
  • Consider whether you really _need_ to get updates as frequently as that, or whether every 10, 20 or 30 seconds would be sufficient. If it _really_ needs to be as real-time as every 2 seconds, then re-design your application to use Websockets or Server Sent Events instead of AJAX. (You'd probably benefit from doing that anyway to be honest, even with a less frequent update cycle.) – ADyson Oct 14 '21 at 08:42

0 Answers0