Home > Software design >  React Native clearInterval is not stoping setInterval
React Native clearInterval is not stoping setInterval

Time:01-08

For some reason I can't get my counter to stop. The function receive the 'stop' on the onPressOut however clearInterval() is not working the counter continues to run

  const startCounter = press => {
    let myInterval = setInterval(() => {
      setCounter(count => count   1);

      if (press === 'stop') {
        clearInterval(myInterval);
      }
    }, 1000);
  };

  return (
    <Pressable
      onPress={toggleMute}
      onLongPress={startCounter}
      onPressOut={() => startCounter('stop')} />
  )

CodePudding user response:

Try this code it's work !

let myInterval = '';
  const startCounter = press => {
    myInterval = setInterval(() => {
      setCounter(count => count   1);

      if (press === 'stop') {
        clearInterval(myInterval);
      }
    }, 1000);
  };
  const stopCounter = () => {
    clearInterval(myInterval);
  }
  return (
    <Pressable
      onPress={toggleMute}
      onLongPress={startCounter}
      onPressOut={() => stopCounter()} />
  )
  •  Tags:  
  • Related