Search code examples
javascriptsetintervalclass-method

JavaScript: Utilizing setInterval() to call a class method


I am making a simple clock utilizing class methods. Here is the code:

class clock{
  constructor(date){
    this.hour = date.getHours();
    this.minute = date.getMinutes();
    this.second = date.getSeconds();
  }

    updateHours(){
      if (this.hour==24){
        this.hour= 0;
      } else this.hour++;
    }
    updateMinutes(){
      if (this.minute==60){
        this.minute= 0;
        this.updateHours();
      }
      else this.minute++;
    }

    updateSeconds(){
      if (this.second ==60){
        this.second = 0;
        this.updateMinutes();
    } else{this.second++;}
      return (console.log(`${this.hour}:${this.minute}:${this.second}`)); 
}
}

let date = new Date();
let myClock = new clock(date);

setInterval(myClock.updateSeconds(), 1000);


CASE #1:

The above outputs one line and never repeats. In the debugger, the program seems to just get stuck at the setInterval() line and never goes back into the supplied function. Why is this the case?

=====

CASE #2:

  • setInterval(myClock.updateSeconds, 1000)

When I do not include the parenthesis for the function, I should be getting the function description, correct? Why does this output undefined:undefined:NaN

=====

CASE #3:

  • setInterval("myClock.updateSeconds()", 1000)

When I put quotations around the function, everything starts working perfectly

=====

Please elaborate on the functionality of setInterval() and how these cases relate. I though I have the correct idea (in the sense that the function is simply evaluated and accepts a returned value as done so in Case 1). Anything helps! Thanks!


Solution

  • You are not using setInterval correctly. You need to pass in a function or class method that will be executed at a later time. Currently, you are executing the method yourself, and you are passing a return value from that method to the setInterval

    You also need to bind the method to the instance of your class, because when you pass a method to the setInterval it loses the this reference. this will point to the window object` not to the instance of your class.

    Do it like this:

    setInterval(myClock.updateSeconds.bind(myClock), 1000);
    

    codesandbox example

    Mdn Function.bind()