5

I would to create a timer in my App. I created a timer as:

var timer = document.getElementById('timer');
var rest = 90;
timer.innerHTML = rest + 's';
var interval = setInterval(function(){
  if(rest <= 0){
    clearInterval(interval);
   }else{
     rest -= 1;
    timer.innerHTML = rest + 's';
  }
  
}, 1000);
<div id='timer'></div>

But, when the user leaves my app (NOT KILL, JUST LEAVE) and go to any other app, the timer stops working.

And when he comes back to my app, the timer starts working.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Charly berthet
  • 1,178
  • 5
  • 15
  • 31

2 Answers2

4

This question is a copy to the following:

How can I run background tasks in React Native?

The following answer is written: Currently, there is, unfortunately, no support for background tasks of any kind. The feature you are referring to would be a background timer. Such a timer is this product plain (a feature request) for react native, you may upvote it to show an increased demand for this feature.

(There is no update yet. As far as i know)

Community
  • 1
  • 1
Jonathan Stellwag
  • 3,843
  • 4
  • 25
  • 50
  • For me background task could be use when your application is killed. In my case is I just want the timer not stopped when the user just lock his phone. – Charly berthet Jul 03 '16 at 06:49
  • The only option i see for you to make your 'background-task' possible is to completely implement it native. But therefore i have not the experience to give u the right answer. I just found 2 links wich i will share to you and maybe they help you: https://facebook.github.io/react-native/docs/native-modules-android.html https://developer.android.com/training/run-background-service/create-service.html – Jonathan Stellwag Jul 03 '16 at 07:16
-7

I have use a trick.

var that = this;
  for(var i = 1; i <= that.state.restSec; i++){
    setTimeout(function(){
      //do your stuff here
    }, i * 1000);
  }

When you come back timeouts are updated like they have worked during the "onpause" :).

Charly berthet
  • 1,178
  • 5
  • 15
  • 31