Pressing the button it generates a countdown to request a new password. After this gets to 0 you get a new link to request it. The issue is when during existing countdown I am pressing the button. It seems somehow I am running in the same time 2 counters and not sure how to fix this. Can you please help:
https://codepen.io/acode2/pen/poaWpmv
<form class="olr-form">
<input
data-sc-field-name="secondsToNextOTP"
value="30"
>
<p class="passcodeReRequest">Don't have a valid passcode?</p>
<button type="submit" class="button__next button__test">Test</button>
</form>
const opt = () => {
$('.test').remove();
$('.otpLinkAvailable').remove();
let gCountdownTimerHandle = 0;
let gDateTimeForNextOTP = null;
// getting the seconds to cowntdown
let secsToNextOTP = $("[data-sc-field-name=secondsToNextOTP]").val() * 1;
if (secsToNextOTP) {
let passCodeResendlink = $(".passcodeReRequest");
Date.prototype.addSecs = function (s) {
this.setTime(this.getTime() + (s * 1000));
return this;
}
// this function is polled and updates the status of time until a new OTP request can be made by the user
function showTimeToWaitForOTP() {
try {
const linkAvailableInTag = $(".otpLinkAvailable");
const secondsToNextOTP = Math.round((gDateTimeForNextOTP - new Date()) / 1000);
if (linkAvailableInTag && linkAvailableInTag.length > 0) {
if (secondsToNextOTP > 0) {
linkAvailableInTag.text(" you can re-request a passcode in " + secondsToNextOTP + " seconds");
} else {
clearInterval(gCountdownTimerHandle);
linkAvailableInTag.text("");
linkAvailableInTag.after(" <a class='test' href='javascript:document.location = document.location+\"&resendOTP=true\"'>Send a new passcode</a>");
}
}
else {
clearInterval(gCountdownTimerHandle);
}
} catch { // any errors, cancel the timeout
clearInterval(gCountdownTimerHandle);
}
}
// // check if we need to trigger the OTP countdown timer
if (passCodeResendlink && passCodeResendlink.length > 0 && secsToNextOTP >= 0) {
gDateTimeForNextOTP = new Date().addSecs(secsToNextOTP);
passCodeResendlink.append("<span class='otpLinkAvailable'></span>");
gCountdownTimerHandle = setInterval(showTimeToWaitForOTP, 500); // issue countdown
}
}
}
$(".button__test").click(function(e) {
e.preventDefault();
opt();
});
gCountdownTimerHandle should be outside the opt() function. Each time you are clicking the button - you are resetting gCountdownTimerHandle to 0 at line number 3 inside opt() function. That is why your clearInterval is not capturing the actual id of setInterval and hence it is not getting cleared.
Hope it helps!