0

I get this error with the first code snippet below

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'unsafe-inline'".

    class SomeClass {
     constructor(){
           
        this.startTime = 0;
        this.gameTimer = setInterval(this.myTimer(), 1000);

    }

    myTimer() {
        this.startTime++;
        document.getElementById('time-count').innerHTML = this.startTime;

    }
}

But with a lambda function everything works fine:

    class SomeClass {
      constructor(){

         this.startTime = 0;
         this.gameTimer = setInterval(() => {
             this.startTime++;
             document.getElementById('time-count').innerHTML = this.startTime;
         }, 1000);
        
    }
}

I would like to know is there a way to declare a method or a function that I can set as an argument in the setInterval function (what I'm calling the constructor) without getting the 'unsafe-eval' - error ?

Ps. It would be a great plus to also know why I'm getting the error in the first snippet.

BuggedBit
  • 5
  • 6
  • 1
    In the first code example, you are passing `undefined` as a callback to `setInterval` (`this.myTimer()` returns `undefined`) – blex Mar 21 '21 at 19:00
  • So should I pass the myTimer function to the constructor as an argument and define it outside of the SomeClass class? – BuggedBit Mar 21 '21 at 19:04
  • You should be able to pass the method directly, but you will need to bind the `this` context to it: `setInterval(this.myTimer.bind(this), 1000);` – blex Mar 21 '21 at 19:06

0 Answers0