Display the dynamic change of minutes and seconds every second on an Ionic HTML page

I created a JavaScript countdown counter that displays minutes and seconds using the following line of code:

document.getElementById("demo").innerHTML = Number(this.minutes) + 'm' + Number(this.seconds) + 's ';

However, on iOS devices, it shows NANm NANs due to this line. I need to find another method to show minutes and seconds.

Below is my TypeScript code:

if ((this.Fajardistance <= '59') && (this.Fajardistance >= '0')) {

    let current_datetime = new Date()
    let formatted_date = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate()
    console.log("formatted_date", formatted_date);

    // Set the date we're counting down to
    var countDownDate = new Date(`${formatted_date.toString()} ${value.fajar_iqamah}`).getTime();        
    console.log("countDownDate", countDownDate);

    // Update the count down every 1 second
    this.intervalTime = setInterval(function () {

      // Get today's date and time
      var now = new Date().getTime();

      // Find the distance between now and the countdown date
      var distance = countDownDate - now;

      this.testing = false;
      // Calculate minutes and seconds
      this.minutes = Math.floor((Number(distance) % (1000 * 60 * 60)) / (1000 * 60));
      this.seconds = Math.floor((Number(distance) % (1000 * 60)) / 1000);

      // Display minutes and seconds in desired output
      console.log("Minutes:", this.minutes);
      console.log("Seconds:", this.seconds);

      // Commented out incorrect way of displaying minutes and seconds for iOS devices
      //document.getElementById("demo").innerHTML = Number(this.minutes) + 'm' + Number(this.seconds) + 's ';

      // If the countdown is over, hide the element 
      if (distance < 0) {
        clearInterval(this.intervalTime);

        document.getElementById("demo").style.display = "none";
      }

    }, 1000);

  }

Home.html

<!--<span mode="md" id="demo" style="text-align:right;font-size: 16px; display:inline-block;margin-left: 16px;  margin-top: 0px; color:red;"></span>-->

I previously used the above commented method to display the countdown but found it was not suitable for iOS devices.

Answer №1

Your code has several crucial issues that need to be addressed.

  1. Can you please clarify the purpose of value.fajar_iqamah?
  2. The calculation countDownDate - now may cause your interval to run only once, as now will likely always be greater than countDownDate.
  3. Even if you reverse the calculation to now - countDownDate, the distance will continuously increase instead of decreasing, creating an unintended effect.

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

Enhancing Type Safety in Typescript through Key/Property Type Guards

Is it possible to create a typeguard that can confirm the existence (or specific type) of a property in an object? For example: Consider an interface Foo: interface Foo { bar: string; baz: number; buzz?: string; } An object of type Foo may ...

Transform an array of Boolean values into a string array containing only the values that are true

Suppose we have an object like the following: likedFoods:{ pizza:true, pasta:false, steak:true, salad:false } We want to filter out the false values and convert it into a string array as shown below: compiledLikedFoods = ["pizza", "steak"] Is t ...

`How can we efficiently transfer style props to child components?`

Is there a way to pass Props in the Style so that each component has a unique background image? Take a look at this component: countries.astro --- import type { Props } from 'astro'; const { country, description } = Astro.props as Props; --- & ...

Using variables to replace 'placeholders' in Typescript with string interpolation

Seeking a definitive answer on this matter, I pose the question: In C#, an example of which would be as follows: var text = "blah blah"; var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah' How can I accomplish t ...

Converting a String variable to a String Literal Type in Typescript: A step-by-step guide

When working with Typescript, imagine I need to call a function that has the following signature- function foo(param: "TRUE"|"FALSE"|"NONE") Is there a way to achieve something like this- var str = runtimeString() if(str === "TRUE" | str === "FALSE" | s ...

Having difficulty creating a TypeScript function

I've encountered a TypeScript error that has left me puzzled: src/helpers.ts:11:14 - error TS2322: There's an issue with this piece of code and I can't quite grasp it: Type '<T extends "horizontal" | "vertical" | undefined, U extends ...

Creating an Inner Join Query Using TypeORM's QueryBuilder: A Step-by-Step Guide

Hello there! I'm new to TypeORM and haven't had much experience with ORM. I'm finding it a bit challenging to grasp the documentation and examples available online. My main goal is to utilize the TypeORM QueryBuilder in order to create this ...

Beautiful ExpressionChangedAfterItHasBeenCheckedError

I need your help Input field where I can enter a Student email or IAM, which will be added to a string array List displaying all the students I have added, using a for loop as shown below Delete button to remove a student from the array The list has a sp ...

In the scenario where I have a nested readonly array within an object, what is the best way to duplicate that object and transform the array to allow for mutations (such as inserting into Akita)?

Suppose I have the following TypeScript interface: interface Member { readonly id: number; readonly name: string; readonly email: string; groups: <ReadonlyArray>Group } interface Group { readonly id: number; readonly name: string; ...

What is the best way to utilize await in promises instead of using then?

How can I correctly handle the Promise.all() method? I'm experiencing issues with resolving the promise that generates a series of asynchronous requests (simple database queries in supabase-pg SQL). After iterating through the results with a forEach l ...

Restoring previous configuration in Ionic2 from the resume() lifecycle method

Encountering an issue with my ionic2 application where I save the last state in local storage when the app goes to the background. Upon resuming, it checks for the value of lastState in local storage and pushes that state if a value exists. The specific er ...

Give it a little time before uploading a widget onto the page

As a newcomer to programming, I recently came across this code from an open source project. I am in the process of loading a widget onto a website. Instead of having the widget load instantly, I would like it to wait 10 seconds before displaying. Below i ...

"Encountering issue with auto-import suggestions failing to appear in VS Code version 1.88.0

After installing the necessary libraries for MUI, I encountered an issue where basic components like Typography were not showing up in intellisense. Instead, it was displaying @mui/icons-material. You can view screenshots below: https://i.stack.imgur.com/ ...

Angular validation for password and confirmation password fields

I have been working on implementing password and confirm password validation within an angular project. I recently came across a helpful answer on this thread Confirm password validation in Angular 6 that I tried to follow. Unfortunately, I am encountering ...

How to Properly Retrieve an Array of JSON Objects Using Ionic 3 Storage

Storing and retrieving an array of JSON objects locally with Ionic storage: Country[5] 0: {record_id: "1", local_TimeStamp: "16:00:00", country: "USA"} 1: {record_id: "2", local_TimeStamp: "17:00:00", country: "Japan"} 2: {record_id: "3", local_TimeStamp: ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

Error: The render view is unable to read the 'vote' property of a null object

Within this component, I am receiving a Promise object in the properties. I attempt to store it in state, but upon rendering the view, I encounter the error message "TypeError: Cannot read property 'vote' of null." Seeking a solution to my predic ...

Angular 6 - Build a dynamic single page housing various applications within

I am faced with the task of developing multiple applications using Angular 6. Each application will have its own set of components, services, and more. However, there is also a need for shared services, components, directives, and other elements that will ...

Having trouble getting TypeScript to compile on Visual Studio Online TFS?

Currently, I am utilizing Typescript 1.7 within an MVC environment. Locally, my Typescript functions properly and compiles without any issues. However, when integrating with visualstudioonline TFS for continuous integration to an azure website, I have enc ...

Exploring the depths of Rx.ReplaySubject: Techniques for delaying the `next()` event

Confused Mind: Either I'm mistaken, or the whiskey is starting to take effect. (I can't rule out the possibility that I'm just going crazy. Apologies for that.) Assumption: My assumption was that ReplaySubject would emit a single value eve ...