Search code examples
javascripttimersetintervalweb-worker

Run a Javascript code on an inactive browser tab every n hours


I need to run a piece of Javascript code on a web page every 24 hours. I wrapped that code inside setInterval. That works, when the tab is active. However, when I come back after 24 hours I don't see it working. From my research on the internet, it appears that scripts on inactive tabs are de-prioritized by browsers. I see solutions based on Web Workers. Are there simpler alternate solutions to this problem?


Solution

  • Finally, I have a solution to my problem in question. I used "visibilityState" event to detect when an inactive tab is clicked, I also had a window scope variable that I used to record the last time when my script had executed(window.globalVar.lastProfileTime). Using both, I introduced this logic:

    const lastProfileTime = window.globalVar.lastProfileTime;
    if((document.visibilityState === 'visible') &&
        ((typeof(lastProfileTime) === 'undefined') || 
        ((currentTime - lastProfileTime)  >  86400000))) { 
        // do something
    }

    This way, whenever user brings the browser tab into view, the visibilityState eventlistener triggers, and based on the 24hour check executes the piece of code I need. This way no timers required.