javascriptmobiletimersleep

Does JavaScript timeout continue to execute while a mobile device is asleep?


I'm working on an application that needs to measure the amount of time that has passed between user inputs. I'd prefer to use a timeout, but could store the time value as a variable and figure out how long has passed. This web app will be used primarily on mobile devices. Will JavaScript figure out if the timeout has been exceeded if the device goes to sleep between the time the timeout is set and the end time?


Solution

  • Short answer: no. The script will not be executed when the mobile browser is switched into the background.

    More complex answer: if the mobile device enables background application AND if the browser decides to give the page priority, the script continues to execute. So far this is not the case in most devices, certainly not an iPhone.

    Having said that, you can use a timeout function regardless. When the user resumes the page, the function is still triggered. Timeout events are only "frozen", but not canceled. The timing clock is also suspended, so you'll have to remember the actual time, and compare that when the "wake up time". Use setInterval to pull this deadline. If timeout arrives sooner, cancel the Interval callback.

    Thanks for this question. It got me thinking.