Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to setInterval in react component constructor? [duplicate]

I need to setInterval when main component. i tried setting it in constructor like

  constructor(props) {
    super(props);
    this.props.fetchUserInfo();
    this.props.fetchProducts();
    setInterval(console.log('1'), 1000);
  }

or inside componentDidMount

  componentDidMount = () => {
    setInterval(console.log('1'), 1000);
  };

but it always logs '1' once. How to launch interval properly?

like image 603
Ilya Lopukhin Avatar asked Nov 17 '25 11:11

Ilya Lopukhin


1 Answers

setInterval(console.log('1'), 1000); calls console.log('1') and passes its return value into setInterval, exactly the way foo(bar()) calls bar and passes its return value to foo.

You want to pass a function reference to it:

setInterval(function() {
    console.log('1');
}, 1000);

Or if you need this to be the same inside that function and are not yet using ES2015 syntax:

setInterval(function() {
    console.log('1');
}.bind(this), 1000);

Function#bind returns a new function that, when called, calls the original using the this value you give it.

Or if you are using ES2015 syntax

setInterval(() => {
    console.log('1');
}, 1000);

That will close over the this where it's created, no need for bind.

like image 67
T.J. Crowder Avatar answered Nov 20 '25 00:11

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!