繁体   English   中英

反应本机取消 setTimeout

[英]react native cancel setTimeout

我想在我的本机应用程序中实现“正在输入”消息。 我正在使用 websockets 发送消息。

我已经实现了一个 useEffect function ,每当消息 state 发生变化时都会调用它(这个 state 包含用户当前正在输入的消息)。 每当message.length % 2 === 0和“正在输入”套接字消息时,都应该发送。 2 秒后,应发送一条新消息“停止输入”。

let timeout;

// useCallback function depending on message and timeout
// this function checks the length of the message and sends
// a start typing socket message
// after 2 seconds, an end typing socket message should be send
// OR this should be cancelled if the user is still typing
const isTypingFunction = useCallback(() => {
  if (message.length > 0 && message.length % 2 === 0) {
    if (timeout) {
      clearTimeout(timeout);
    }
    socket.send(__start_message_here__);
    timeout = setTimeout(() => {
      socket.send(__end_message_here__);
    }, 2000);
  }
}, [message, timeout]);

// useEffect function to run the isTypingFunction
useEffect(() => {
  isTypingFunction();
}, [message]);

问题是:之前的 setTimeout没有被取消。 当我开始打字时,在另一个控制台中,我看到开始打字的消息来了,但过了一会儿,结束打字的消息也来了。 我只希望实际发送 1 条结束输入消息(最后一条)。

您没有通过渲染保留timeout变量,因此您无法取消之前的超时。 您可以使用useRef通过渲染保留任何值。 试试这个代码:

const timeoutHandle = useRef(0);

// useCallback function depending on message and timeout
// this function checks the length of the message and sends
// a start typing socket message
// after 2 seconds, an end typing socket message should be send
// OR this should be cancelled if the user is still typing
const isTypingFunction = useCallback(() => {
  if (message.length > 0 && message.length % 2 === 0) {
    clearTimeout(timeoutHandle.current);
    socket.send(__start_message_here__);
    timeoutHandle.current = setTimeout(() => {
      socket.send(__end_message_here__);
    }, 2000);
  }
}, [message]);

// useEffect function to run the isTypingFunction
useEffect(() => {
  isTypingFunction();
}, [message]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM