Languages
[Edit]
EN

JavaScript - window focus lost event (trick for older web browsers)

0 points
Created by:
Welsh
902

In this article, we would like to show you a simple trick to handle window focus lost event using JavaScript.

This solution is based on the fact, that the setInterval() method is slowing down on window focus lost.

Note: This is a trick that works both in modern and older web browsers.

Practical example

Edit

In this example, we calculate the time between intervals to check for major changes. When the setInterval() method slows down, we know that the window focus has been lost.

Run the following example and switch between the tabs for a while to see the result:

Note:

We set the interval to 0.8s (800ms), but when you switch the tab it slows down to >1000ms. However, when you focus back to the current window it "equalizes" the difference (so it can be < 800ms).

Uncomment line 6 in the code above to see time elapsed between intervals.

Reusable function

Edit

 

References

Edit
  1. setInterval() - Web APIs | MDN

Alternative titles

  1. JavaScript - window focuslost event (solution for older web browsers)
  2. JavaScript - window onfocuslost event (solution for older web browsers)
  3. JavaScript - window onblur event (solution for older web browsers)
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join