【发布时间】:2026-02-23 01:30:01
【问题描述】:
在我的 react-native 应用程序中,我试图使用 clearTimeout 停止 setTimeout。我将setTimeout 的一个实例保存在一个全局变量中。
let timeoutId:any = null;
const doOtp = ()=>{
if(canSendOtp) {
setCanSendOtp(false);
timeoutId = setTimeout(() => { // it has here a numeric value
showNotificationMessage("You can request OTP again")
setCanSendOtp(true)
}, SEND_OTP_TIME_CONSTRAINTS)
// rest of doOtp logic
}
else {
showNotificationMessage("Please wait " + (SEND_OTP_TIME_CONSTRAINTS / 1000) + " seconds before trying again")
}
}
然后当我想使用 clearTimeout 停止 setTimeout 时,我看到 timeoutId 的值是 null。我不明白为什么会这样。
const doLogin = () => {
issueToken(LOGIN_GRANT_TYPE, LOGIN_CLIENT_ID, LOGIN_CLIENT_SECRET, phoneNumber, otp)
.then(res => {
console.log('timeoutId !== null' + timeoutId !== null)
if(timeoutId !== null) { // value here is null - why?
clearTimeout(timeoutId)
}
store().dispatch(setTokenValidity(res))
})
.catch(err => {
showNotificationMessage('Error, something went wrong check logs.')
console.log("issueToken error: " + JSON.stringify(err))
});
}
【问题讨论】:
-
仅从那些代码 sn-ps (以及关于代码结构的一些有利假设)这应该可以工作 -> 请添加minimal reproducible example
标签: javascript typescript settimeout cleartimeout