katzer / cordova-plugin-background-mode

Keep app running in background
Apache License 2.0
1.38k stars 1.02k forks source link

Time doubles when using countdown timer in background #333

Open thestevenmellor opened 6 years ago

thestevenmellor commented 6 years ago

I have a countdown timer that runs in the background using observables but the time doubles when put in background mode. Thoughts?

Abul22 commented 6 years ago

Probably because its getting reduced cpu priority once in background. How's the timer implimented?

If its something like a setTimeout/setInternval ... Perhaps it might be better structured like below where its not requiring every tick to increment itself.

var endTime = 412341412; if(now >= endTime){ //timer ended }else{ console.log( (now/endtime)*100 + " % completed" ) }

thestevenmellor commented 6 years ago

Yeah it's a pomodoro timer... code is below:

timerTick() { setTimeout(() => { if (!this.runTimer) { return; } this.remainingTime--; this.displayTime = this.getSecondsAsDigitalClock(this.remainingTime); if (this.remainingTime > 0) { this.timerTick(); }else { this.hasFinished = true; console.log("time's up"); } }, 1000); }

I don't know how to implement your version, but I wonder if I could just set a condition that if it's in background mode, to divide the timer by 2.

dimitriscsd commented 6 years ago

Timers in javascript are annoyingly inaccurate... When the app gets put in the background it does indeed put in secondary priority for the CPU, hence slowing down it's timers.

Have you tried the option that disables webview optimisations? I doubt it will be perfect to the milisecond but you might find it helps a bit.

m52go commented 6 years ago

this is coming late but i just had the same issue in my app. i have to run a timer on every page of my app, with the timer continuing on every new page from where the last page left off.

for me it was events not being unsubscribed that were causing the timers to be sparked more than once on every page entrance.

subscribing on page enter & unsubscribing on page exit did the trick for me. not sure if your situation is similar.