Wiem, że rozpoczynanie interwału w useEffect
jest łatwe do usunięcia tak:
useEffect(() => {
const interval = setInterval(some function, time);
return () => clearInterval(interval)
})
Ale co, jeśli muszę ustawić interwał w funkcji, jak wyczyścić interwał w tej sprawie, czy po prostu nie muszę?
const startGame = () => {
const interval = setInterval(some function, time);
}
useEffect(() => {
startGame()
})
2
Code Eagle
22 czerwiec 2020, 20:38
3 odpowiedzi
Najlepsza odpowiedź
Możesz użyć haczyka useeffect , aby usunąć interwał
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;
1
urvashi
22 czerwiec 2020, 18:11
Myślę, że tego chcesz:
var ctr = 0, interval = 0;
var startGame1 = () => {
ctr++;
clearInterval(interval);
console.log("hello")
if(ctr>=5){
clearInterval(interval);
}else{
interval = setInterval(()=>{startGame1()}, 1000);
}
}
startGame1()
1
ABGR
22 czerwiec 2020, 18:14
Użyj tego kodu na przykład:
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;
1
majid savalanpour
22 czerwiec 2020, 18:56