How to run a background JavaScript in Phonegap on iPhone – for timer/stopwatch?

My stopwatch script runs flawlessly in the background on Android (counting up the time), but iOS 4.3.2 seems to pause the script. On iOS the stopwatch stops at the time where the application was sent to background.

I need a runnning stopwatch (the time appears updated each second in the view) and some alarm messages in defined points in time.

  • RestKit 0.20.1 How to map parent id
  • Button action in mkannotation view not working?
  • Xcode 7 Install of Apple Watch Application never finished
  • bootstrap 3 accordion collapse does not work on iphone
  • Binding UDP Socket to Cellular IP
  • Which is the best method to display thumbnail images on UIScrollview (downloaded from server)
  • The code for the stopwatch is as below:

            this.timer = window.setInterval(function(){
                instance.runtime += Stopwatch.INCREMENT;
                instance.doDisplay();
            }, Stopwatch.INCREMENT);
    

    I’m aware of native solutions, but would like to stick with a JavaScript solution for the sake of cross-platform compatibility.

    Solutions Collect From Internet About “How to run a background JavaScript in Phonegap on iPhone – for timer/stopwatch?”

    Since setIntervals don’t work in the background I’d use a recursive setTimeout instead.
    Which means you can’t keep track of time with a +=, so you’ll need to use a (new Date).getTime(); or Date.now() instead.

    this.timer = function myTimer () {
      instance.currentTime = (new Date).getTime();
      instance.doDisplay();
      setTimeout( myTimer, Stopwatch.INCREMENT ); 
    }
    

    If the setTimeout doesn’t come back to life when the app does it should be simpler to restart.