2

I have a script which called a JS function every 2.5 seconds. This is the code that I use,

<script type='text/javascript'>
    getMsgs();
    setInterval(function() {
      getMsgs();
    }, 2500);
</script>

This code keeps on executing even if I am on an other tab on the browser. How can I make this only execute when the tab with that specific page is open?

  • look into http://www.thefutureoftheweb.com/blog/detect-browser-window-focus – Muhammad Usman Jan 05 '18 at 08:38
  • Duplicate, look https://stackoverflow.com/questions/13957980/javascript-should-run-only-if-tab-browser-window-is-focused and https://stackoverflow.com/questions/7389328/detect-if-browser-tab-has-focus – AGoranov Jan 05 '18 at 08:39
  • refer this https://stackoverflow.com/questions/38361392/execute-javascript-code-once-a-browser-window-tab-is-opened-for-the-first-time – Swati Singh Jan 05 '18 at 08:39
  • Possible duplicate of [Is there a way to detect if a browser window is not currently active?](https://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active) – Robby Cornelissen Jan 05 '18 at 08:39
  • Possible duplicate of [Detect If Browser Tab Has Focus](https://stackoverflow.com/questions/7389328/detect-if-browser-tab-has-focus) – Marcel Jan 05 '18 at 08:45

2 Answers2

2

As stated in an answer here, you could use

window.onfocus and window.onblur
AGoranov
  • 2,114
  • 3
  • 15
  • 27
1

An approach would be to check whether document.hidden is false

   setInterval(function() {
         if(document.hidden === false) {
             getMsgs();
         }
    }, 2500);
Manav
  • 1,357
  • 10
  • 17