When does Windows sleep?

I have always wondered about a somewhat inconsistent behaviour in how Windows decides when the computer is inactive, and to turn off the screen and subsequently sleep. As an example, if I have a 2 hour YouTube video playing in the browser, the screen will never turn off and the computer will not go to sleep while the video is playing.

However, if I have a finance website open that constantly refreshes stock prices every minute via client side JavaScript, the screen will turn off and the computer will go to sleep according to the Power Settings configured on the machine.

In both scenarios, the keyboard and mouse is never moved, and my attention is captivated by the YouTube video or the constantly refreshing stock prices, but somehow Windows decides that the latter scenario is considered inactivity.

I finally chanced upon the answer earlier today while examining Windows APIs. Apparently, according to the documentation, the SetThreadExecutionState function takes in the ES_DISPLAY_REQUIRED flag as well as the ES_SYSTEM_REQUIRED flag which resets the respective idle timers. It is actually the browsers themselves which decide whether a particular activity is worthy of being kept alive and reset the timers at a regular interval.

While browsers implement keep alive for media playback by default, they do expose a Screen Wake Lock API that programmers can use to stop the screen from turning off. The System Wake Lock was present in a previous version of the API but was removed, possibly to prevent misuse.