如何清除已经启动并正在运行的`setInterval`函数的间隔。

huangapple go评论133阅读模式
英文:

How to clearInterval of the function that has started and running with setInterval?

问题

如何在设置worker值为"0"时停止loadFriendList的加载?

const [worker, setWorker] = useState('1');

function start() {
  setInterval(loadFriendList, 5000);
}
useEffect(start, []);

function n() {
  setWorker("0");
  Alert.alert('check', worker);
}
英文:

how to stop the loadFriendList when setWorker Value is"0"?

const [worker, setWorker] = useState('1');
 
function start() {
 setInterval(loadFriendList,5000);
}
useEffect(start, []);
 
function n() {
  setWorker("0");
  Alert.alert('check', worker);
}

答案1

得分: 2

不要将字符串用作数字,这是不必要的麻烦。
使用useRef钩子来存储intervalID。
useEffect钩子在worker更改时触发。
!在[]中看到我们添加了worker变量。这被称为依赖数组。基本上,你在告诉useEffect观察这些变量,并在任何变化时触发。

useEffect(() => {
  if (worker === 0) intID.current && clearInterval(intId.current)
}, [worker])

useRef钩子保持页面加载时设置的Interval,以唯一标识并在将来运行clearInterval()等方法。

最终应该如下所示

const [worker, setWorker] = useState(1);
const intId = useRef(null)

useEffect(() =>{
  intId.current = setInterval(loadFriendList, 5000);
  return () => clearInterval(intId.current)
}, []);

useEffect(() => {
  if (worker === 0) intId.current && clearInterval(intId.current)
}, [worker])
英文:

>Don't use strings as number it's an unnecessary hassle .

> use useRef hook to store intervalID .

This useEffect hook fires whenever worker is change.
>! see inside the [] we've added worker variable. It's called dependancy array. Basically you're saying to useEffect look on these variables and fire if anything changes

useEffect(() => {
  if(worker == 0) intID.current && clearInterval(intId.current)
},[worker])

The useRef hook is holding on to the Interval you set up when page loading, to uniquely identify and run methods like clearInterval() in future

Finally It Should Look Like

const [worker, setWorker] = useState(1);
const intId = useRef(null)
 
useEffect(() =>{
  intId.current = setInterval(loadFriendList,5000);
  return () => clearInterval(intId.current)
}, []);
 
useEffect(() => {
  if(worker == 0) intId.current && clearInterval(intId.current)
},[worker])

答案2

得分: 0

const [worker, setWorker] = useState('1');
const [intervalId, setIntervalId] = useState(null);

function start() {
setIntervalId(setInterval(loadFriendList, 5000));
}

useEffect(start, []);

function n() {
setWorker("0");
clearInterval(intervalId);
Alert.alert('check', worker);
}

英文:
const [worker, setWorker] = useState('1');
const [intervalId, setIntervalId] = useState(null);

function start() {
  setIntervalId(setInterval(loadFriendList, 5000));
}

useEffect(start, []);

function n() {
  setWorker("0");
  clearInterval(intervalId);
  Alert.alert('check', worker);
}

huangapple
  • 本文由 发表于 2023年3月15日 19:29:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744088.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定