sadanandpai / frontend-mini-challenges

Collection of frontend challenges for learning and interviews
https://sadanandpai.github.io/frontend-mini-challenges/
MIT License
2.02k stars 494 forks source link

[React/traffic-lights]: Timer lags behind lights after switching tabs #325

Closed arpansaha13 closed 11 months ago

arpansaha13 commented 11 months ago

Framework/code-stack

React

Scope

Traffic lights

Description

After opening the traffic lights challenge (or refreshing the page), the timer and lights update together, which is the expected behavior.

But after switching tabs the timer slows down and the lights and timer no longer update together.

Possible Reasons The browser throttles the setInterval when the tab is inactive to reduce CPU consumption. Hence both timers no longer update at expected intervals.

Expected behaviour

The timer and lights should update together. The lights should change after the timer ends irrespective of tab switching.

Suggested Solutions

Instead of using two separate useEffect for duration and lights, perform all updates in a single useEffect.

Additional Context

No response