我試圖實作這樣一種情況,即第一次在 X 秒后執行 setTimeout 中的函式,然后以 Y 間隔定期執行。
useEffect(() => {
let firstTime = true;
const timer = setTimeout(() => {
getValue(id).then((res) => {
setValue(res);
});
if (firstTime) {
firstTime = false;
}
}, firstTime ? 30000 : 60000);
return () => clearTimeout(timer);
}, [])
但是,這不起作用,因為它firstTime在運行該函式之前設定為 false。有沒有辦法優雅地實作結果?甚至有可能setTimeout嗎?
uj5u.com熱心網友回復:
您可以使用變數作為setTimeout延遲。在這種情況下,您可以將firstTime第一次使用的延遲設定為 (30000),然后在計時器內部使用if (firstTime == 30000) { firstTime = 60000; }. 在這里使用不同的變數名是有意義的。然后將setTimeout延遲設定為firstTime就像}, firstTime);
希望這實際上是您想要的。
useEffect(() => {
let firstTime = 30000;
const timer = setTimeout(() => {
getValue(id).then((res) => {
setValue(res);
});
if (firstTime == 30000) {
firstTime = 60000;
}
}, firstTime);
return () => clearTimeout(timer);
}, [])
舊(不正確)答案:
您可以使用setTimeout初始延遲來初始化 a setInterval,它將以不同的間隔重復后續時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398175.html
標籤:javascript 反应 设置超时
下一篇:如何將SWR與泛型T一起使用?
