The problem is that when the tab/window is hidden, browser doesn’t redraw its content but the script continues to run, and when you switch back, it catches up at the first script execution that cause a redraw.
What you could do is use the Page Visibility API and stop script from running when tab/window is non visible
solved JS / CSS Transition when Window not active