javascript - Cordova/PhoneGap: setInterval() / setTimeout() not working correctly -
i implemented simple countdown timer using window.setinterval. works in desktop browser not work correctly on smartphone (fairphone 2) phonegap/cordova app. according examinations , research on internet interval/timeout interrupted when phone sent sleep/standby. that's why not work.
astonishingly interval/timeout not interrupted when phone connected via usb cable computer. it's energy-saving feature that's causing bad behaviour.
so, i'm lost. don't know how implement simple countdown timer of course should work when phone sleeps (=display turned off). there alternative window.setinterval() / window.settimeout() ?
here simple code (as stated: window.settimeout not work, either):
... <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="js/libs/jquery.js"></script> <script> var min = 25; $(document).ready(function(){ intervalid = window.setinterval(function () { --min; if (min > 0) { $("#countdown").text(min); } }, 6000); }); </script> ... <p id="countdown">0m</p>
use interval timer updating display. use system time decide display.
then, if interval doesn't called when display not visible, no problem. next time called (when display turned on again), calculate correct elapsed time system time , display correctly.
for reason (and several others), should never assume setinterval() going keep perfect time. in javascript, means want called every once in while , set approximate time specify frequency, interval may shut off long periods of time.
get time when interval starts date.now() , each time interval fires, new system time , subtract start time see how time has elapsed , calculate want display.
if want show minutes remaining on 25 minute timer, this:
function showtimer(selector, minutes) { var starttime = date.now(); var interval; function showremaining() { var delta = date.now() - starttime; // milliseconds var deltaminutes = delta / (1000 * 60); if (deltaminutes < minutes) { // display minutes remaining $(selector).text(math.round(minutes - deltaminutes)); } else { $(selector).text(0); clearinterval(interval); } } interval = setinterval(showremaining, 15 * 1000); showremaining(); } $(document).ready(function(){ showtimer("#countdown", 25); }); working demo: https://jsfiddle.net/jfriend00/807z860p/
Comments
Post a Comment