0

I'm running the following code and i'm not able to find a better solution to run mutiple setTimeouts without causing performance issues. I have an array with 102 records, the application is lagging for about 5 seconds and works finely after launching functions.

    const animateMarker = React.useCallback(() => {
    let delay = 0;
    if (props.routes.coordinates[0]) {
      props.route.coordinates.slice(1).map((point: Point, index) => {
        const idTimeout = setTimeout(() => {
          if (busRef.current) {
            busRef.current.animatedMoveTo(
              {
                lat: point.lat,
                lon: point.lon,
              },
              10000,
            );
          }
        }, delay);
        setTimeOuts(prevTimeOuts => [...prevTimeOuts, idTimeout]);
        delay += 10000;
      });
    }
  }, [props.routes]);

const clearAllTimeouts = React.useCallback(() => {
    timeouts.map(timeout => {
      clearTimeout(timeout);
    });

    setTimeOuts([]);
  }, [timeouts]);

  React.useEffect(() => {
    animateMarker();
    return () => {
      clearAllTimeouts();
    };
  }, [animateMarker]);

I'm looking for any solution or suggestions I read something something about using threads, is there any solution for this sort of problem Should i look to something else like threads or something ? should i change map functions to something like for loop ? is it better to launch setTimeouts in the same time ? or seperate them with slice like for exmaple calling the first 30 records with slice and the others after that

Zero0
  • 371
  • 4
  • 15
  • basically, you're calling setTimeouts sequentially with increasing delays right? – Vin Xi Nov 15 '22 at 14:07
  • Yes, i'm like moving the marker to the next point so, the marker takes a certain delay and i'm increasing it everytime – Zero0 Nov 15 '22 at 16:21
  • why don't you use setInterval for that – Vin Xi Nov 16 '22 at 05:46
  • I'm using setTimeout beacause delays are different betwen them, it's just an example. but i think that setTimeout is the better solution for my case – Zero0 Nov 16 '22 at 11:56
  • Ah, I understand, in that case. Look into this thread for learning requestAnimationFrame and webworkers for threading if the need arises. Hope this helps https://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome/12522580#12522580 – Vin Xi Nov 16 '22 at 12:33
  • this is for react is there any solution for react native ? – Zero0 Nov 16 '22 at 17:10
  • In react-native look into react-native-reanimated worklets – Vin Xi Nov 17 '22 at 05:36

0 Answers0