I'm struggling to find out how to keep my Javascript countdown keep showing correct numbers even when user's mobile screen goes off (with and without screen lock).
I've a simple JS countdown -
// I set the time_remaining during page load
let time remaining = $("#time-remaining).val();
let countdown = setInterval(function () {
let minutes = Math.floor(time_remaining / 60);
let seconds = time_remaining % 60;
// Code to displaying minutes and seconds in html
// goes here.
if(time_remaining === 0) {
clearInterval(countdown);
}
}, 1000);
Now, in order to compensate for the halted setInterval, I make use of the visibilitychange event as follows -
$(document).on('visibilitychange', function() {
if(document.visibilityState === 'visible') {
axios.get('/get-time-remaining')
.then(function (response) {
time_remaining = response.data.time_remaining
});
}
});
That is, whenever the user screen gets visible, I fetch the time remaining from server and update my time_remaining variable.
This approach works okay; does introduce a bit of delay but does the job.
However, I've observed that visibilitychange triggers ONLY WHEN user's mobile screen has screen-lock enabled.
If the user unlocks the mobile; visibilitychange event is triggered and I get my time_remaining as expected.
However, without a screen-lock, that even is not triggered; and thus, the countdown does not function properly.
I've considered different approaches such as -
-
Polling the server every few seconds and fetch the correct time remaining; and adjust the countdown on user's mobile.
-
Making use of service worker; but I'm not exactly sure how to make it work.
-
Maybe there's some other JS event that gets triggered when the user has the browser window 'focused' or 'visible'; on which I can trigger my AJAX call to the server to get correct time remaining.
Would really appreciate if you could help figure out a proper solution to this problem.