我正试图停止setInterval函数,该函数在单击后每100毫秒生成一个随机数,但我的clearInterval不会执行任何操作。
import React, {useState} from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
export default function App() {
const [randomNumber, setRandomNumber] = useState ('CLICK');
const generateRandomNumber = () => {
setInterval(() => {setRandomNumber(Math.floor(Math.random() * 100) + 1 )}, 100);
};
const stopWheel = () => {
clearInterval(generateRandomNumber);
console.log(randomNumber);
};
const spinWheel = () => {
generateRandomNumber();
setTimeout(stopWheel, 2000);
};
return (
<View>
<TouchableOpacity onPress={spinWheel}>
<Text>{randomNumber}</Text>
</TouchableOpacity>
</View>
);
};
答案 0 :(得分:1)
这是因为您要清除功能而不是间隔。尝试这样的事情:
let timer;
const generateRandomNumber = () => {
timer = setInterval(() => { setRandomNumber(Math.floor(Math.random() * 100) + 1) }, 100);
};
const stopWheel = () => {
clearInterval(timer);
console.log(randomNumber);
};