Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
Javascript Countdown timer shuffles between two timers

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.

enter image description here

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda