skip to Main Content
<Button titleStyle={{color: "white",fontSize: 14, fontWeight: 500}}
    title={recording ? 'Stop Recording' : 'Start Recording'}
    onPress={recording ? stopRecording : startRecording}
/>

Let’s say I press the button and the recording starts, how do I stop the recording after 60 seconds if the user hasn’t already pressed the button again to stop the recording?

2

Answers


  1.  const [time, setTime] = useState(60);
     // I think you are recording initially and want to stop after 60
     const [recording, setRecording] = useState(true);
     // you have to keep track of if user has pressed on the button or not
     const [pressed,setPressed]=useState(false)
     // in each second we update this and check if its current value is 0
     // you could set the timer with useState but it would cause unnecessary rerenderings
     let timerRef = useRef();
    
    const countDown = () => {
        setTime((prev) => prev - 1)
        if (time===0){
           setRecording(false)
        }
    };
    
    useEffect(() => {
        // every second call countDown
        timerRef.current = setInterval(countDown, 1000);
        // when user pressed on button, in its callback, write setPressed(true)
        // or in onPressed callback you could `clearInterval(timerRef.current)`
        if(pressed){
            clearInterval(timerRef.current)
        }
        return () => clearInterval(timerRef.current);
      }, [pressed]);
    
    Login or Signup to reply.
  2. let timeoutId;
    
    const startRecording = () => {
      timeoutId = setTimeout(() => {
        stopRecording();
      }, 60000); 
    }
    
    const stopRecording = () => {
      clearTimeout(timeoutId);
    }
    

    setTimeout() function is used to start a timer that calls the stopRecording() function after 60 seconds.

    clearTimeout() function is used to cancel the timer if the user presses the stop button .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search