If you happen to use React, I built a React component that helps you manage this! :) Hopefully it helps a bit! It also reports whether or not a user is idle, such that you can reduce cpu usage during that as well.
In general, the mantra for people who find this tough to fix should be, "Why didn't I use MVC, what a cretin I was!"