1

I have the following code:

/* MY CLASS */
class Cronometer{
    constructor(){
    }

    getKey(key){
        return JSON.parse(localStorage.getItem('taskRunning'))[key];
    }

    initCronometer(currentTask){
        var startDate = new Date().getTime();

        var config = {
            "startDate": startDate,
            "currentTask": currentTask
        };

        localStorage.setItem('taskRunning', JSON.stringify(config));
       

        var idInterval = setInterval(function(){
            var time = this.convertToTime( new Date().getTime() - this.getKey('startDate') );
            console.log(time);
        }, 1000);

        return idInterval;
    }

}

/* RUN */
var c = new Cronometer();
c.initCronometer(5555);

when I run the c.initCronometer(5555), I receive this message:

Uncaught TypeError: this.getKey is not a function

Somebody can tell me why that error is showing?

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 1
    Put the error message in the question, not an image of it.... – epascarello Sep 17 '18 at 20:43
  • 2
    https://stackoverflow.com/questions/2749244/javascript-setinterval-and-this-solution – epascarello Sep 17 '18 at 20:44
  • get rid of the `this` keyword, which is no longer referencing the class scope because its inside a callback function when being called. – Redtopia Sep 17 '18 at 20:49
  • you may use setInterval additional param: setInterval(function(obj){....obj.getKey('startDate') );}, 1000, this); – gaetanoM Sep 17 '18 at 20:51
  • The value of /this/ inside your callback won't be bound to your instance when the callback is actually invoked. You could use the arrow-function syntax (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Zunino Sep 17 '18 at 20:54

1 Answers1

0

Change your Interval code to the following:

 var idInterval = setInterval(() => {
        var time = this.convertToTime( new Date().getTime() - this.getKey('startDate') );
        console.log(time);
    }, 1000);

You should use arrow functions in such cases to not loose the context(“this” pointer).

When using usual function(anonymous functions) they create a new “this” inside themselves.