I have the following Javascript codes
// COUNTDOWN TIMER
function refillTimer(refillTimer){
var countDownDate = new Date(refillTimer).getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var hours = ("0" + Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))).slice(-2);
var minutes = ("0" + Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))).slice(-2);
var seconds = ("0" + Math.floor((distance % (1000 * 60)) / 1000)).slice(-2);
document.getElementById("refillTimer").innerHTML = hours + ":" + minutes + ":" + seconds;
if(distance < 0){
clearInterval(x);
document.getElementById("refillTimer").innerHTML = "00:00:00";
}
}, 1000);
}
// ON SWIPE PERFORM ACTION
async function swipeAction(currentElementObj, swipeType) {
var cardId = currentElementObj.getAttribute("value");
var dataString = {
card: cardId,
swipe: swipeType
};
let response = await new Promise((resolve, reject) => {
try {
var xhr = new XMLHttpRequest();
xhr.open("POST", "processes/swipe.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.responseType = "json";
xhr.send(JSON.stringify(dataString));
xhr.onreadystatechange = function () {
let resObj = xhr.response;
if(xhr.readyState == 4 && xhr.status == 200 && resObj) {
if(resObj.action == 'gameover'){
refillTimer(resObj.nextgameoverTimer);
}else if(resObj.action == 'killsalloted'){
refillTimer(resObj.nextkillsallotedTimer);
}
}
};
}catch(e){
reject(e.toString());
}
});
}
As you can see in the swipeAction() function I have two if and else if conditions on success where I call the timers. The problem here is that once the timer is called under one condition then on being called on the other condition the timer overlaps each other. This should not happen. The timers should load individually. Which technically means that the timer function should be refreshed every time it is called or something similar. Please look at the GIF below for exact problem.
Here, one condition calls a 12 hour timer while the other calls a 24 hour timer. Both the timer are overlapping each other as shown above instead of showing the respective one only. What can be the required solution?
Put return x into refillTimer. Put let timer at the top of swipeAction, change both refillTimer(...) into timer = refillTimer(...). Put clearInterval(timer) above if(resObj.action...).
Alternately, change var x = setInterval(...) to timer = setInterval(...) (no var; also, avoid x as variable name, especially if it has a larger scope). Put let timer in front of function refillTimer(...) { ... }. Put clearInterval(timer) at the start of refillTimer function.
Either of these courses of action will ensure that you clear the previous interval timer before installing a new one, and thus have only one running at a time.