Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval function without arrow function

I am learning about react components following the documentation https://facebook.github.io/react/docs/state-and-lifecycle.html

Why do we need to use arrow function here:

this.timerID = setInterval(() => this.tick(), 1000);

Why can't I just say (obviously it doesn't work)

this.timerID = setInterval(this.tick(), 1000);
like image 970
gvaswani Avatar asked Aug 20 '17 09:08

gvaswani


3 Answers

Why do we need to use arrow function here

Answer is simple : see the result inside live script example...

class Persons{

    scopeOne(){
          // your will see the result this will display our current object 'Persons'
          setInterval(function(){
          
              console.info(' SCOPE ONEo : '+this);
          
          },3000);    
    }
    scopeTwo(){
          setInterval(function(){
          
              console.info(' SCOPE TWO : '+this);
          
          }.bind(this) ,3000);
    }
    
    scopeThree(){
        setInterval(() => { console.info(' SCOPE THREE : '+this) },3000);
    }
}

let p = new Persons();
    p.scopeOne();
    p.scopeTwo();
    p.scopeThree();

in first scope the result is WINDOW OBJECT so we cannot access our current class scope so in 2nd scope we using scope with bind(this) that helps to bind our current object scope, and in third which do same as 2nd scope calling the current object....

like image 136
user12143633 Avatar answered Oct 21 '22 11:10

user12143633


The first argument for setInterval is of type function. If you write this:

this.timerID = setInterval(this.tick(), 1000);

…then you don't pass a function, instead you execute the function this.tick immediately and then pass the value returned by that function call as an argument.

You could write it like this:

this.timerID = setInterval(this.tick, 1000);

If you omit the parentheses, you pass a reference to your this.tick function, which is then executed by setInterval after 1000 milliseconds.

like image 11
Patrick Hund Avatar answered Oct 21 '22 11:10

Patrick Hund


setInterval takes function as first argument, in the second case it is getting a returned value

Change it to

this.timerID = setInterval(this.tick.bind(this), 1000);

or

 this.timerID = setInterval(() => this.tick(), 1000);

which is probably what you need when you want to bind the function to the React context.

See this answer on why you need to bind functions in React

If you don't you could have simply written

this.timerID = setInterval(this.tick, 1000);
like image 9
Shubham Khatri Avatar answered Oct 21 '22 12:10

Shubham Khatri