Home > Blockchain >  callback function (arrow) and class method in TimeOut
callback function (arrow) and class method in TimeOut

Time:01-31

I want to trigger 2 functions with a unique timeOut.
The following works fine

    setTimeout(function() {
      function1(); // runs first
      function2(); // runs second
    }, 1000)

But in my case, I have a class method and an callback (arrow function).
It looks like this (minimalized):

    class Timer {
      constructor(callback) {
        this.active = false;
        this.callback = callback;
      }

      cancel() {
        this.active = false;
      }

      set() {
        this.active = true;
        this.timeOut = setTimeout( function() {
          this.cancel();
          this.callback; // HERE is my problem. doesn't run, not casted as a function
        }, 1000)
      }

I get the following error Expected an assignment or function call and instead saw an expression. Any trick to fix that?

CodePudding user response:

You are not calling callback function, you can also add type check before calling.

set() {
  this.active = true;
  this.timeOut = setTimeout(() => {
    this.cancel();
    typeof this.callback === 'function' && this.callback();
  }, 1000)
}
  •  Tags:  
  • Related