The timer functionality in the Angular 2+ component is malfunctioning

This situation is quite perplexing. I have a timer function that works perfectly on all my components except one. Strangely, I can't seem to figure out why this particular component is not cooperating, especially since there are no error messages appearing.

What could I be missing? Here is the code structure that I am using:

The HTML snippet:

<p>Time in milliseconds: <b id="tick">{{time}}</b></p>

and in my protected.component.ts file:

timeBegin = new Date();
  starts = null;
  time = '00:00:00.000';

GetUser(): void {
    this.startTime();
    this.dataService.getUser().subscribe(res => {
      if (res !== undefined) {
        this.dataIsReady = true;
        this.imgSrc = 'data:image/png;base64,' + res['image'];
      }
    });
    this.stopTime();
  }

public clockRun() {
const currentTime = new Date();
const timeElapsed = new Date(currentTime.getTime() - this.timeBegin.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

this.time =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 99 ? ms : ms > 9 ? '0' + ms : '0' + ms);


}

  startTime() {
    this.timeBegin = new Date();

    this.starts = setInterval(this.clockRun.bind(this), 10);
  }

  stopTime() {
    clearInterval(this.starts);
  }

Answer №1

Perhaps a simpler way to approach this is by using DatePipe in HTML, like so:

{{ interval | date:'HH:mm:ss SSS':'+0000'}}

Within the component, you can set it up like this:

  timeBegin: Date;
  interval: Date;

  ngOnInit() {
    this.timeBegin = new Date();
    setInterval(this.tick.bind(this), 100);
  }

  tick() {
    let currentTime = new Date();
    this.interval = new Date(currentTime.valueOf() - this.timeBegin.valueOf());
  }

In your example, you immediately stop the timer which may prevent you from seeing progress. Consider executing stopTime within the subscribe block, like this:

GetUser(): void {
    this.startTime();
    this.dataService.getUser().subscribe(res => {
      if (res !== undefined) {
        this.dataIsReady = true;
        this.imgSrc = 'data:image/png;base64,' + res['image'];
      }
      this.stopTime();
    });
  }

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

Running a Custom Tab Component in a React Application

I am currently facing an issue with my React app that has multiple tabs. When I click on a specific tab, I want only that tab to render, but currently all tabs are rendering when I click on one. I have used console.log to confirm that all tabs are indeed r ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...

Tips on how to direct the attention to a text box within a unique dialog, ensuring that the blinking cursor highlights the input area

Is there a way to set autofocus on a textbox when opening a custom dialog box? I've tried using the autofocus attribute for the input field, but it doesn't seem to work for me. Can anyone provide guidance on how to achieve autofocus for a textfie ...

What could be causing PHP to fail to send form scores to the PHP MyAdmin database?

I recently ventured into web development and took on a college project website where I built a form in HTML containing various radio button questions. To handle the validation of answers against the correct ones, I utilized JavaScript. With some assistance ...

Trouble arises with kids when trying to adjust the display to block mode

I need to set all the div elements inside the div with id "editor" to display as block. However, when I change the display property of the div with id "editor", only that specific div's display is affected, while everything else inside the div becomes ...

Dealing with 404 errors encountered when making requests to external websites, utilizing either basic Javascript or JQuery

I have links in my application that redirect to external websites. For example, a link might look like this: <http://www.google.com'>>General Search<>. Users input the href and we dynamically create the link without any validation of it ...

Sending multiple text fields along with a file to an API using Angular

I'm currently facing a challenge with uploading a file to an API endpoint that I created using Laravel, using an HTML form. The upload works fine when only the file is involved. However, I also need to include some basic text fields in the request. T ...

Event bubbling does not occur in elements outside of the DOM

I am facing an issue with a DOM element that has not been added to the DOM yet, but I want to trigger a DOM event on it. The event is not supposed to bubble up, however, when using jQuery, it does. This behavior seems odd to me. This strange phenomenon c ...

Remove the attribute from the element in the ng-repeat loop

Here is my ng-repeat code snippet: <th ng-repeat="field in tableFields" translate="{{field.headerTitle | translate}}" ts-criteria="{{field.sortable ? field.fieldKey : null}}"> <label class="i-checks" ng-if="field.isCheckbox"> & ...

What could be the reason behind the validation failure of this Javascript code?

After implementing your recommendation, this is my current status: <script> function tick() { const React.element = ( '<div><marquee behavior="scroll" bgcolor="lightyellow" loop="-1" width="100%"> <i> <font color ...

How do I define two mutations in a single component using TypeScript and react-apollo?

After exploring this GitHub issue, I have successfully implemented one mutation with Typescript. However, I have been unable to figure out how to use 2 mutations within the same component. Currently, there is only a single mutate() function available in t ...

Utilizing a JavaScript variable in a separate file: A guide

I am facing a JavaScript challenge where I have a variable that changes its value on a particular event. Now, I need to access this variable in a different file for some calculations. For instance, in my index.php file, I have the following variable: ...

Ways to handle Sessions in Node.js

I'm attempting to utilize a website within node.js. However, the site is prompting me to enable the storage of session cookies. I attempted to set up a cookie-jar, but I couldn't get it to work. Here is a simplified version of the code that is c ...

The issue with making an HTTP POST request in Angular 2

Service: postJson() { var json = JSON.stringify({ "key": "CT", "values": ["FSP", "HMC", "PHYP","hell"] }); let headers = new Headers({'Content-Type':'application/json'}); //let options = new RequestOptions({ ...

Ways to obtain the scrollWidth and offSetWidth of a div that is being utilized as an ngx-datatable-cell-template within an ngx-datatable

How can I retrieve the scrollWidth and offSetWidth of a div that is included in a child component being loaded as an ngx-datatable-cell-template inside ngx-datatable? I am consistently receiving values of 0. I have added a template variable for the div el ...

What is a clever way to monitor the completion of a forEach loop using promises?

I'm new to promises and I'm attempting to use them for the first time. After the completion of the forEach loop, I want to call another function for additional processing. However, when using forEach, the function insertIDBEvents is only printed ...

Customize Swiper js: How to adjust the Gap Size Between Slides using rem, em, or %?

Is there a way to adjust the spacing between slides in Swiper js using relative units such as 2rem? The entire page is designed with relative units. All measurements are set in rem, which adjusts based on the viewport size for optimal adaptability. For i ...

Passing optional inputs in Angular using ngx-charts is a simple and convenient

Currently delving into Angular 8 and ngx-charts. My goal is to showcase graphs sourced from configuration files. To achieve this, I have enabled the configuration file to offer multiple graphic options (essentially encompassing most options available at ) ...

How to Implement Click Actions on Elements in AngularJS

Just starting out with angularjs and I have a scenario with jQuery. handleClick(); function handleClick() { var doubleClick = false; $('#text span.word').on('click', function() { var that = this; setTimeout(funct ...

nodemon was not properly installed on the system

I attempted to add nodemon to my application using the command below: npm install nodemon -g This is the output that was generated: changed 116 packages, and audited 117 packages in 8s 16 packages are looking for funding run `npm fund` for details fou ...