Search code examples
javascriptgoogle-chromegoogle-chrome-extensionsetinterval

setInteval in background script


I am developing a browser extension for a real-time product. I have a background page with "persistent : true" set in the manifest.json (I am using version v2). I am continually polling the server for new data every second using setInterval(). The background script also caches the data it has gathered till present and gives it to any newly opened tab.

Things work fine until sometimes I noticed that when I put the computer to sleep for a long period, my poll to server just stops! If I refreshed any of the existing tabs, I do see cached data. This means, that the background page was not killed by Chrome. My question is, why is chrome just stopping the setInterval() call? Also, what is the correct way to revive the poll if it's stopped for some reason?

//relevant part of manifest.json
  "background": {
    "scripts": [
      "js/background/jquery.min.js",
      "js/background/bgconfig.js",
      "js/background/backgroundmanager.js",
      "js/background/eventsfetcher.js"
    ],

    "persistent": true
  },

Thanks!


Solution

  • For anyone else looking for the solution, I ended up implementing what @Pluto suggested :

    "Store the intervalID returned from setInterval in a global variable, then when the window gains focus again, clear that interval and run setInterval again"
    

    This has worked well for me so far with no dropped events from server.