[英]How to clear interval in functional component if interval is set in a function?
我知道在useEffect
中开始一个间隔很容易像这样清除:
useEffect(() => {
const interval = setInterval(some function, time);
return () => clearInterval(interval)
})
但是,如果我必须在 function 内设置一个间隔,在这种情况下如何清除间隔,或者根本不需要?
const startGame = () => {
const interval = setInterval(some function, time);
}
useEffect(() => {
startGame()
})
您可以使用thw useEffect hook 来清除间隔
import React, { useEffect } from "react";
const Timer = () => {
const interval = React.useRef();
const startGame = () => {
interval.current = setInterval(() => {
//code
}, 3000);
};
React.useEffect(() => {
return () => {
clearInterval(interval.current);
};
}, []);
};
export default Timer;
例如使用此代码:
import React, { useEffect, useRef } from 'react';
const Timer = () => {
let interval = useRef();
const startGame = () => {
interval.current = setInterval(() => {
// your code
}, 1000)
}
useEffect(() => {
startGame();
return () => clearInterval(interval.current)
})
return (
// your jsx code;
);
};
export default Timer;
我想这就是你想要的:
var ctr = 0, interval = 0; var startGame1 = () => { ctr++; clearInterval(interval); console.log("hello") if(ctr>=5){ clearInterval(interval); }else{ interval = setInterval(()=>{startGame1()}, 1000); } } startGame1()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.