Home > Back-end >  React doesn't update state when browsing a different website or application
React doesn't update state when browsing a different website or application

Time:01-14

I am currently learning react right now. I am following a react tutorial for a stopwatch application where it just increments the time every second. The code perfectly works as it indeed increments the time every second. However, if I open a new browser tab, or even open a different application, it seems that react doesn't update the state, meaning, the timer stops incrementing the value. But if I visit the react application, it begins to increment (once again).

I literally watch the timer go to '00:00:10' and then click another tab and wait for about 10 seconds. When I go back to the react application, the timer is still at '00:00:11', instead of '00:00:20'.

Is there something I am missing? Why is react behaving this way? It is because of performance issues? I am pretty sure this is a nature of react but I can't seem to find an explanation anywhere else.

I am also not sure if I should provide the code for the stopwatch application as I am sure that it's not a bug, nor a problem relating to the code itself. Let me know if I need to include the code so that I can edit this question.

CodePudding user response:

If your website isn't active (in an active browser tab) then the Browser doesn't execute your JavaScript code. It does that to save CPU time - people tend to have a lot of tabs open.

For a timer application you want to remember the timer start time (e.g. with new Date().getTime()) and then every second you calculate the difference to this start time. This way if the user leaves the tab and comes back then the timer is correct again after latest a second.

Another benefit is that your timer will be more accurate even if the browser tab remains focused all the time. The timer calls aren't exact so your code isn't called exactly every second, but only about every second and the errors sum up over time. If you have a start time available then these errors don't matter.

Edit: There is more to this topic, the best thing I could find quickly is this discussion How do browsers pause/change Javascript when tab or window is not active?

  • Related