Within my react-native application, I am attempting to halt the execution of a setTimeout
function by utilizing clearTimeout
. The instance of setTimeout
is stored in a global variable.
let timeoutId: any = null;
const doOtp = () => {
if(canSendOtp) {
setCanSendOtp(false);
timeoutId = setTimeout(() => { // a numeric value is present here
showNotificationMessage("You can request OTP again")
setCanSendOtp(true)
}, SEND_OTP_TIME_CONSTRAINTS)
// additional logic for doOtp
}
else {
showNotificationMessage("Please wait " + (SEND_OTP_TIME_CONSTRAINTS / 1000) + " seconds before trying again")
}
}
However, when attempting to stop the setTimeout
using clearTimeout, I encounter an issue where the value of timeoutId
is null
. This occurrence is puzzling to me.
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) { // the value at this point is null - the reason remains unclear
clearTimeout(timeoutId)
}
store().dispatch(setTokenValidity(res))
})
.catch(err => {
showNotificationMessage('Error, something went wrong check logs.')
console.log("issueToken error: " + JSON.stringify(err))
});
}