SetTimeout无限循环和运行函数一次
SetTimeout infinite loop and run function once
我需要减少 setInterval 函数的网络调用量。每 3 秒,调用 API。第一个 API 有时需要更长的时间才能收到服务器的响应。
代码
useEffect(() => {
const id = setInterval(async () => {
console.log('hello')
await callAPI()
console.log('bye')
}, 3000);
return () => {
clearInterval(id);
};
})
Problem
setInterval 函数每 3 秒调用一次 callAPI 方法,而第一次调用 API 方法仍在 运行 等待服务器响应,这导致许多 API 调用这是垃圾邮件服务器。
Expected
SetInterval 函数应等待第一个调用方法的响应,然后每 3 秒再次调用 运行 方法。
我只想使用一个自称的 setTimeout
:
useEffect(async () => {
let id;
const api = async () => {
console.log('hello')
await callAPI()
console.log('bye')
id = setTimeout(api, 3000);
});
await api();
return () => {
clearTimeout(id);
};
})
例如:
const api = () => {
console.log('hi');
setTimeout(api, 1000);
console.log('bye');
}
api();
const Example = props => {
const [countdown, setCountdown] = React.useState(100);
React.useEffect(() => {
const timeout = setTimeout(() => {
setCountdown(countdown - 1);
}, 1000);
return () => {
clearTimeout(timeout);
}
}, [countdown]);
return (<div>{countdown}</div>)
}
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="react"/>
我需要减少 setInterval 函数的网络调用量。每 3 秒,调用 API。第一个 API 有时需要更长的时间才能收到服务器的响应。
代码
useEffect(() => {
const id = setInterval(async () => {
console.log('hello')
await callAPI()
console.log('bye')
}, 3000);
return () => {
clearInterval(id);
};
})
Problem
setInterval 函数每 3 秒调用一次 callAPI 方法,而第一次调用 API 方法仍在 运行 等待服务器响应,这导致许多 API 调用这是垃圾邮件服务器。
Expected
SetInterval 函数应等待第一个调用方法的响应,然后每 3 秒再次调用 运行 方法。
我只想使用一个自称的 setTimeout
:
useEffect(async () => {
let id;
const api = async () => {
console.log('hello')
await callAPI()
console.log('bye')
id = setTimeout(api, 3000);
});
await api();
return () => {
clearTimeout(id);
};
})
例如:
const api = () => {
console.log('hi');
setTimeout(api, 1000);
console.log('bye');
}
api();
const Example = props => {
const [countdown, setCountdown] = React.useState(100);
React.useEffect(() => {
const timeout = setTimeout(() => {
setCountdown(countdown - 1);
}, 1000);
return () => {
clearTimeout(timeout);
}
}, [countdown]);
return (<div>{countdown}</div>)
}
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="react"/>