Stop the timer from halting when running in the background

Currently, I have a timer implemented in my Ionic3 application. The timer functions smoothly with a setInterval method; however, it poses an issue when the App is put into sleep mode as the timer stops running. Upon reopening the App and bringing it to the foreground, the timer does resume, but it picks up from where it left off before pausing.

I am seeking advice on how to prevent the timer from halting when the App is sent to the background.

This is part of my component:

time: any;

displayTime() {
  this.time = moment().hour(0).minute(0).second(this.counter++).format('HH : mm : ss');
}

startTime() {
  if(this.runClock == null) {
    this.runClock = setInterval(() => {
      this.displayTime();
    },1000)
  }
}

The time display in my HTML is called using {{ time }}.

Unfortunately, utilizing plugins like https://ionicframework.com/docs/native/background-mode/ is not an option since Apps incorporating this plugin may face rejection by the App Store.

Are there any alternative suggestions to address this issue?

Answer №1

When developing an app that operates in the background, it is important to consider the guidelines set forth by the App Store to avoid rejection (and for good reason - nobody wants an app that unnecessarily drains battery life). To address this issue without relying on a setInterval counter and background mode, the following approach can be taken:

startMoment = moment();

displayTime() {
  this.time = moment.utc( moment().diff(this.startMoment) ).format('HH : mm : ss');
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing properties for objects with map-like characteristics

Many interfaces allow for arbitrary data, as shown below: interface Something { name: string; data: { [key: string]: any }; } The problem arises when trying to access or set values on objects with arbitrary keys in Typescript. let a: Something = { ...

What steps should I take to prevent my <mat-card> from expanding whenever messages are shown in Angular 9?

I have a <mat-card> containing a login form on my page. However, when error messages are displayed, the vertical size of the <mat-card> changes and I need it to remain the same. Is there a way to prevent this from happening? Below, you will ...

Distinguishing variations within subcategories that stem from a common origin

In my code example, I have two interfaces that both extend a common base interface. The "String" function takes an argument of type "StringAsset". My expectation was that if I were to call the "String" function and pass it a value of "NumberAsset", TypeScr ...

There is no matching signature for Type when using withStyles

Struggling to convert my React App to typescript, I keep encountering the error below and cannot decipher its meaning. The app functions perfectly in plain JS. My package version is material-ui@next TS2345: Argument of type 'typeof ApplicationMenu&a ...

Error message from fake backend interceptor: "The username 'undefined' has already been used."

I am currently following a tutorial on creating a basic signup/login feature using a fake backend interceptor. I have successfully implemented the signup component, user model, and service with the required endpoints for the fake API. However, when I attem ...

Employing a provider within a different provider and reciprocally intertwining their functions

I'm currently facing an issue with two providers, which I have injected through the constructor. Here's the code for my user-data.ts file: @Injectable() export class UserDataProvider { constructor(private apiService: ApiServiceProvider) { ...

Combining React, Typescript, and asynchronous Promises

Currently I am in the process of developing a component that interacts with a webservice to fetch data asynchronously using promises. Once the promise is fulfilled, I intend to integrate the results into my component's rendering method. My ultimate go ...

Discovering a discrepancy in Angular’s documentation: when using a template reference variable, it does not

One thing that has caught my attention in the Angular Documentation is an example related to Angular template input variables. I tested this code snippet myself, hoping that the text entered in the input box would appear next to it as mentioned in the docu ...

How to update Angular Material table dynamically after CRUD operation without needing to reload the page

Hello, I am currently using Angular (v.9) along with ASP .NET Core Web API and EF Core (v 3.1) to perform CRUD operations. I have a region component form which is used as a dialog, you can view it https://i.stack.imgur.com/6w7hO.png The HTML code for the ...

Troubleshooting: In Angular 9 Material, the span element is not properly displaying the value selected from

Currently, I am tackling a project that involves creating a custom component to incorporate Angular Material's mat-select. The issue at hand is that while the data and value for select options (mat-option) are correctly populated in the business logic ...

Calculating the total sum of an array utilizing filter and reduce techniques

How can I calculate the total value of all my products in the list by adding numbers together? this.totalValue = this.items.filter((item) => item.qtyvalue) .map((item) => item.qtyvalue) .reduce ...

Display the Slug in the Website URL upon clicking on a Blog Post using Angular and Strapi framework

When a user clicks on a blog, I want the URL to display the slug instead of the ID. My frontend framework is Angular and I have created a service to fetch data from the backend built with Strapi. Currently, when selecting a blog from the view, the URL disp ...

Tips for creating a unit test case in Angular 5 for API failures

Greetings! Currently, I am in the process of developing unit test cases for an Angular 5 application that involves utilizing APIs within the project. While I have successfully completed writing test cases for positive scenarios, I am facing challenges with ...

The error message "Webpack is not applying the style from leaflet.css"

Currently utilizing the ngX-Rocket angular 8 starter, I am looking to integrate the leaflet map library into my project from this source: https://github.com/Asymmetrik/ngx-leaflet After including the file in my index.html document, I encountered the follo ...

Tips for bringing in a text file within a NodeJS application using TypeScript and ts-node during development

I am currently developing a NodeJS/Express application using TypeScript, Nodemon, and ts-node. Within this project, there is a .txt file that contains lengthy text. My goal is to read the contents of this file and simply log it to the console in developmen ...

Angular: No routes found that match the URL segment

I encountered an issue with my routes module where I am receiving the error message Cannot match any routes. URL Segment: 'edit-fighter' when attempting to navigate using the <a> link. The only route that seems to work is the champions-list ...

How can I retrieve specific URL parameters from the in-memory web API in Angular 2?

To retrieve data for a specific unit ID, I am using a parameter called "UnitID" in the following code: this.unitDetailsService.getUnitDetailsbyId(this.activeUnitId) I am utilizing the activeUnitId parameter to generate a URL for an in-memory service with ...

Issue TS2345: Cannot assign type 'UserDataSource' to type '{}'[] in the parameter

I'm having trouble sorting the table using MatTableDataSource... I'm struggling to figure out how to pass an array to MatTableDataSource. I want the data in the table to be displayed and sorted accordingly. //Component.ts file export class Tes ...

Generic type input being accepted

I am trying to work with a basic generic class: export class MyType<T>{} In the directive class, I want to create an @Input field that should be of type MyType: @Input field MyType<>; However, my code editor is showing an error that MyType& ...

Angular 2: Challenges with Utilizing Set - Limited Browser Support and Iteration Issues

I am currently developing an Angular 2 Web Application. My goal is to add users to a game by utilizing checkboxes on a screen. When a checkbox is selected, I plan to add the user to a set. mySet = new Set(); this.mySet.add(e); Once a user clicks the "Ad ...