0

I am using setTimeout in my react native app like this:

run() {

  console.log('test');

  let x = setTimeout(()=>{
    this.run();
  }, 500);
}

componentDidMount() {
   this.run();
}

I tested out 10 components having the code above and render them at the same time and it heavily slows down the app. Is there a way to run multiple setTimeout without affecting the app's performance? Thank you.

Website Is Fun
  • 290
  • 6
  • 20

2 Answers2

1

I figured it out, when setting a setTimeout it is important to assign it in a unique variable. Like:

// for component 1
let loop1 = setTimeout(()=>{
    this.run();
}, 500);

// for component 2
let loop2 = setTimeout(()=>{
    this.run();
}, 500);

// for component 3
let loop3 = setTimeout(()=>{
    this.run();
}, 500);

and so on...

When 10 components sharing the same setTimeout variables, the last component will be prioritized so the last component will be the only one running, the rest will hang up.

My issue is now sorted out. :)

Website Is Fun
  • 290
  • 6
  • 20
0

it's seems your code is recursive but without stopping condition. Basically, you call a function that call herself and so on, without end.

Poptocrack
  • 2,879
  • 1
  • 12
  • 28
  • Yes indeed, it is recursive and I intentionally set it to infinite or no stop to test the number of setTimeout a react native app can handle. – Website Is Fun Aug 10 '17 at 21:58