Having issues with setTimeout on Chrome for Android when the browser is out of focus. Any ideas for resolving this?

I developed a web application that functions as a messaging system, where users can submit messages and others can receive them. The system operates through AJAX, with the front end using JavaScript to interact with a PHP backend. Everything runs smoothly without any issues.

In addition, I integrated a Notification system that sends push notifications to desktop or Android apps when a new message is received. This feature also works flawlessly.

However, the problem arises with the notification system when the Android device is out of focus. The setTimeout function used to periodically check the PHP AJAX system becomes unreliable - sometimes working, sometimes not at all, and sometimes delivering notifications very late.

To address this issue, I attempted to transfer the functionality to a service worker, assuming it would operate independently of the browser focus. Unfortunately, this solution proved to be even worse, with the service worker being even less consistent than using setTimeout in the browser.

Is there a way to resolve this issue? Are there specific directives within the service worker that can be implemented to prevent it from sleeping?

Thank you.

Answer №1

To efficiently manage timers on your webpage, utilize the Page Visibility API to control them based on whether the page is currently in focus or not.

By implementing this API, you can detect when the user switches tabs or minimizes the Chrome app on mobile devices.

document.addEventListener('visibilitychange', function() 
{
    if (document.visibilityState === 'hidden')
    {
        // Pause and save ongoing tasks here
    }
    
    if (document.visibilityState === 'visible')
    {
        // Resume any paused tasks here
    }
});

Another advantage is that it helps conserve bandwidth by pausing refresh timers when the user switches away from your page.

Keep in mind that on mobile, if your page consumes excessive resources, Chrome might unload it from the cache, necessitating a reload when revisited. The document.wasDiscarded flag is set to true after a reload in such cases.

Refer to this informative article and accompanying chart for a deeper understanding of page lifecycle events.

Answer №2

There is no guarantee that timers will run precisely on schedule with this API. Delays caused by CPU load, other tasks, and more are common, leading to potential delays longer than initially planned.

To learn more about the potential delays with the setTimeout function, visit MDN.

If immediate messaging capabilities are essential, consider utilizing an architecture and protocol specifically designed for such purposes. Technologies like WebSockets with event handling would be more suitable for this scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on leaving comments inside a render <div>

Hey there! I'm facing an unusual issue in my React+Webpack project. Even though I marked a line as a comment using //, it still gets rendered in the HTML output. Strangely, I have never encountered this problem before and can't figure out what tr ...

Tips for creating a breakpoint in Sass specifically for a 414px iPhone screen size

For my latest project, I am utilizing sass and looking to incorporate a sass breakpoint or media query. My goal is to have the code execute only if the screen size is 414px or less. Below is my existing code: @include media-breakpoint-down(sm) { .sub-men ...

Add data to a nested array with Vuex

Currently, I am facing a challenge with adding an object to a nested array in Vue using store / vuex. While I have successfully updated the main comments array with a mutation, I am struggling to identify the specific main comment to which the new reply ob ...

The process of passing parameter values by function in useEffect

Hi everyone, I hope you're all doing well. I'm currently facing an issue with trying to retrieve data from my API using the post method. The problem is that I can't use useEffect in any parameter. So, my workaround is to pass the data throug ...

The back-end code on the server is unable to identify the variable in my req.body, as it is being flagged

At the moment, I am in the process of developing a web application that needs to transmit data from the client side to the server side whenever a specific button is clicked. However, when I click the button, the terminal consistently informs me that the va ...

References Not Found in Xamarin Development

I recently attempted to import a Windows library into a Xamarin Android app and encountered the following error: Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'System.Web.Extensions, Version=4.0.0.0, ...

Exploring the concept of JavaScript Variablesqueries

I need help understanding why the results are different in these three examples related to JavaScript. Case 1. var x = 5 + 2 + 3; document.getElementById("demo").innerHTML = x; Result: 10 Case 2. var x = 5 + 2 + "3"; document.getElementById("demo").in ...

The functionality in the app that involves opening another app occasionally disregards the specified feature parameter

Recently, I have been delving into the codelab "Extend an Android app to the Google Assistant with App Actions (Level 2)" and am currently focusing on the step "Add the Open app feature BII capability". I have made the necessary configu ...

Creating a sidebar that remains fixed in place even as the page is scrolled down can be achieved by using CSS and positioning properties

I am looking to create a website with a specific layout design as shown in this image: https://i.stack.imgur.com/ndKcz.png The main focus is on making the sidebar (F/T container) function as a social network link, sticking to the right side of the page ev ...

Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application. res=[ { "url": "/page1", "views": 2 }, { "url": "/page2", "views": 1 }, { "url": "/page1", "views": 10 }, { "url": "/page2", "views": 4 }, { "url": "/page3", "views": 1 }, ...

Combining 2 objects in vue.js that share a common field name

Currently, I am attempting to merge two objects based on a shared key, specifically when they have two fields with the same name but differing values. var players = [{ id : 'a', name : "player1",team:1},{ id : 'b', name : &quo ...

An error was encountered with the startAnimation(anim) method: NullPointerException

I encountered a NullPointerException when trying to execute blah.startAnimation(anim) within a LongClickListener. The scenario involves obtaining the number of children in a GridLayout using a DragListener, and applying an animation to all children when dr ...

How can you avoid Ajax calls from failing due to frequent requests?

Currently, I am utilizing ajax to retrieve some data. However, I have encountered an issue where the ajax request is triggered by hovering over a button, which could potentially result in multiple requests being sent and overwhelming the server, leading to ...

Guide on utilizing the disable feature in SortableJS for a Vue project

I have successfully implemented the draggable effect on my el table using element-ui-el-table-draggable and it's working perfectly. Now, I am looking to incorporate the disable option from SortableJS, but I'm unsure how to integrate these two fu ...

What steps can be taken to address the build problem with Angular version 13?

Encountering a problem while working with Angular 13: https://i.sstatic.net/CbAUhh6r.png Attempting to build using ng build --configuration=test, however facing errors as mentioned above. Interestingly, if I remove the reference to bootstrap.min.css in t ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

Struggling to connect API from React and Node using a proxy server

I have encountered a troubleshooting issue with React and Node that I am struggling to resolve. The problem lies in the communication between my node server and coinmarketcap API. While I successfully receive data from both endpoints (all coins and individ ...

The process of styling with styled components in Mui - a guide to styling

Currently, I am facing challenges with styling and organization while working on a new react project with material ui and styled components. Despite researching best practices for styled components, I am still struggling to find an effective solution for s ...

Retrieve class property in Angular by its name

How can I retrieve an array from a class like the one below without using a switch statement, dictionary, or other collection to look up the name passed into the method? export class ProcessOptions { Arm = [{ name: 'Expedited Review ("ER") ...

"Enhance your web development with Vue.js and Vue-chart.js for beautiful linear

I'm currently struggling to implement a linear gradient background on my Vue-chart.js line chart. Despite searching high and low, the documentation and examples available are not proving to be helpful. After importing the Line component from vue-char ...