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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

oh thanks for quick answer, just forgot how to use that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.