Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

560
Views
Angular2 clock update every second

I've followed the Tour of Heroes tutorial, and I'm now in the process of modifying the project. My project will have a lot of clocks and timers, and my first task is to make a clock that displays the UTC time. With the MomentModule, I'm able to display the time of the page load with:

<p>{{ myDate | amDateFormat: 'ddd Do HH:mm:ss' }}</p>

However, it doesn't update every second like I want it to.

My DashboardComponent looks like this:

export class DashboardComponent implements OnInit {
    heroes: Hero[] =[];
    myDate: Date;

    constructor(private heroService: HeroService) {}

    ngOnInit(): void {
        this.heroService.getHeroes()
            .then(heroes => this.heroes = heroes);

        this.utcTime();
    }

    utcTime(): void {
        setInterval(function() {
            this.myDate = new Date();
            console.log(this.myDate); // just testing if it is working
        }, 1000);
    }
}

So first of all, is it a good idea to create new Date(); every second? Either way, is there a way for update the time in my view every second through something like an observable or similar? Like I said, I'll have a lot of timers and clocks on my page when it's finished. Thanks!

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You just need to use arrowfunction instead of using a traditional function callback syntax as shown below,

setInterval(() => {         //replaced function() by ()=>
  this.myDate = new Date();
  console.log(this.myDate); // just testing if it is working
}, 1000);
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!