setInterval does not work

Asked

Viewed 49 times

0

I’m doing a project that’s a calculator. When loading the page, I would like to show the current date and time. I added the setInterval to update the time every second (I am showing hh-mm-ss) and update the date automatically when needed.

My code so far is like this:

class CalcController {

  constructor() {

    this._locale = 'pt-BR';
    const $ = document.querySelector.bind(document);

    //As próximas três linhas são respectivamente o elemento dos 
    //números da calculadora, a data e a hora no HTML
    this._displayCalcEl = $('#display');
    this._dateEl = $('#data');
    this._timeEl = $('#hora');

    this._displayCalc = '0';
    this._currentDate = new Date();

    this.init();
  }

  init() {

    this._displayCalcEl.innerHTML = this._displayCalc;
    this.setDisplayDateTime();
    //A parte que não está funcionando
    setInterval(() =>  this.setDisplayDateTime(), 1000);

  }

  setDisplayDateTime() {

    this._dateEl.innerHTML = this._currentDate.toLocaleDateString(this._locale, {
      day: '2-digit',
      month: 'long',
      year: 'numeric',
    });
    this._timeEl.innerHTML = this._currentDate.toLocaleTimeString(this._locale);

  }
}

When the page is loaded, it even shows everything I want, the problem is that when updating with setInterval, it doesn’t work.

  • I changed the interval line to setInterval(function () { new CalcController().setDisplayDateTime(); }, 1000); and it worked, but I don’t know why....

  • Depending on where you are running the code will not work with Arrow Function (=>) and with normal Function you would have to use bind to inject scope into Function (function(){...}.bind(this)). About Arrows functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.