1

I am new in javascript and angular. This should be a simple issue but I don't know what is wrong with my code. I don't know if i have the proper syntax for the time handler. The code just display the time only once.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent implements OnInit {

  dateMessage: string;

  constructor() {

  setInterval(this.time_handler, 1000); 

  //Method 1: This works    
  //  setInterval(()=>  {
  //     let currentDate = new Date();
  //     this.dateMessage = currentDate.toLocaleTimeString();
  //  }, 1000);

  }

  ngOnInit() {
  }

// Method 2:  This does not work  
  public time_handler() {
    let currentDate = new Date();
    this.dateMessage = currentDate.toLocaleTimeString();
  }
}    
j08691
  • 204,283
  • 31
  • 260
  • 272
tadpole
  • 1,209
  • 7
  • 19
  • 28

2 Answers2

1

You need to bind this to the function inside the interval.

 constructor() {

  setInterval(this.time_handler.bind(this), 1000); 

  //Method 1: This works    
  //  setInterval(()=>  {
  //     let currentDate = new Date();
  //     this.dateMessage = currentDate.toLocaleTimeString();
  //  }, 1000);

  }

Else this in the handle method won't point to the class.

Vladimir Bogomolov
  • 1,754
  • 13
  • 17
0

The code that does not work because this inside a setInterval will be pointing to window & in window object there is no time_handler function

setInterval(console.log(this), 3000)

That is why your code does not work

But your commented code work because there you are using arrow function, & in arrow function this refers to surrounding scope.

When you use bind that returns a new function and it is explicitly bound

brk
  • 48,835
  • 10
  • 56
  • 78