3

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?

Ilya Lopukhin
  • 672
  • 7
  • 22

1 Answers1

9

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.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639