Marco Disco
Marco Disco

Reputation: 565

React Native - How to delay a start

Hi everybody I'm trying to make a countdown timer with a lot of customizations but my first problem is how to delay the start of it.

It starts with 0 seconds and takes a bit to get the value I passed from the previous page

const CountDownScreen = ({route, navigation}) => {

  const meditationTime = route.params.time;

I take the time

  const getMedTime = () => {
    let res = meditationTime;
    return new Promise(resolve => resolve(res));
  };

state to put the time I'll get

const [timeToGive, setTimeToGive] = useState();


  useEffect(() => {
    const setTimeState = async () => {
      const getTime = await getMedTime();
      console.log('get time', getTime);
      // setGotTime(getTime);

      let timeToGive = {
        minutes: 0,
        seconds: getTime,
      };

      setTimeToGive(timeToGive);
    };
    setTimeState();

    updateTimer();
  }, []);

state with the time

  const [time, setTime] = useState(
    {
      eventDate: moment.duration().add(timeToGive),
    },
  );

the timer starts (I suppose after the PROMISE)

  const updateTimer = () => {
    const x = setInterval(() => {
      let { eventDate } = time;

      if (eventDate <= 0) {
        clearInterval(x);
        sessionEnded();
      } else {

        eventDate = eventDate.subtract(1, 's');

        const mins = eventDate.minutes();
        const secs = eventDate.seconds();

        setTime({
          mins,
          secs,
          eventDate,
        });
      }
    }, 1000);
    setIntervalTime(x);
  };

I tried a lot of different solutions but none worked. It always starts late I would like to avoid a setTimeout is there any better function? Thanks !

Upvotes: 1

Views: 439

Answers (1)

monsty
monsty

Reputation: 633

Thats because you are using setInterval, which starts only after 1 second (in your case).

You should probably readapt your code and do something like that :

  x(); // Call x once

  setInterval(() => {
   x(); 
  }, 1000); // Call x after every seconds

You can store the intervalId into a state, that way you can clear it.

Upvotes: 1

Related Questions