javascript 如果用户尚未按下按钮,如何在60秒后停止录制?

beq87vna  于 2023-03-21  发布在  Java
关注(0)|答案(2)|浏览(162)
<Button titleStyle={{color: "white",fontSize: 14, fontWeight: 500}}
    title={recording ? 'Stop Recording' : 'Start Recording'}
    onPress={recording ? stopRecording : startRecording}
/>

假设我按下按钮并开始录制,如果用户没有再次按下按钮停止录制,我如何在60秒后停止录制?

t3irkdon

t3irkdon1#

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]);
0x6upsns

0x6upsns2#

let timeoutId;

const startRecording = () => {
  timeoutId = setTimeout(() => {
    stopRecording();
  }, 60000); 
}

const stopRecording = () => {
  clearTimeout(timeoutId);
}

setTimeout()函数用于启动定时器,定时器在60秒后调用stopRecording()函数。
clearTimeout()函数用于在用户按下停止按钮时取消计时器。

相关问题