Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval pauses in Android Browser / Mobile Safari when screen times out

I've built a simple JavaScript-based timer for a mobile webapp; for the sake of example:

var a = 0;
setInterval(function() {
    console.log('a', a);
    a++;
}, 1000);

This runs just fine in both Mobile Safari and Android Browser. It will log to console every second and increment the value of a accordingly. (Okay, Android Browser doesn't have console.log support, but let's assume it does.)

The issue: if the screen times out (i.e. user stopped interacting with the page), the setInterval function pauses. It resumes when the user turns on their screen again. This won't work for me as I need timer to keep running.

The questions: Is there a way to prevent the setInterval function from pausing when the screen times out? If not, is it possible to prevent the screen from timing out? Any other alternatives?

Thanks in advance!

like image 206
mjangda Avatar asked Sep 08 '25 01:09

mjangda


1 Answers

Basically, no. The phone enters a sleep state to save battery when the screen times out. Since you can't see anything anyway, a large number of processing tasks are stopped. Similar things will occur when you change tabs/windows (the page is unloaded from memory). Right now there is no way to request that the device stays on from a web application. Future support in Android for accessing hardware may provide this functionality, but personally I doubt it.

If you need always running support, you'll need to write native applications for both systems (plus on Android it can always run).

like image 56
Yann Ramin Avatar answered Sep 11 '25 05:09

Yann Ramin