0
<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?

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
dr7
  • 33
  • 4

2 Answers2

0
 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]);
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
0
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 .

  • Instead of calling stopRecording() I want to programatically press the stop recording button once the 60 seconds have elapsed. How can I do that? – dr7 Mar 21 '23 at 01:39
  • const startRecording = () => { timeoutId = setTimeout(() => { document.getElementById('stopButton').click(); // simulate a click event on the stop button }, 60000); } – Charfeddine Mohamed Ali Mar 22 '23 at 10:53
  • Assuming the stop recording button has an id attribute of stopButton, you can modify the startRecording() function as follows: – Charfeddine Mohamed Ali Mar 22 '23 at 10:54