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

238
Visualizações
Why setInterval and clearInterval is not working in JS?

I am new to JS.

I have 2 cards like the below,

<div class = "card" id ="c1">
     <div class = "content"> </div>
</div>

<div class = "card" id ="c2">
     <div class = "content"> </div>
</div>

The div content in the card 1 should display the dynamic value like Date.now() and the content in card2 should display the static Value.

JS:

function cardData(card) {
    myCard(card);
}

function allCardData() {
    var cards = document.getElementsByClassName("card");
    Array.prototype.forEach.call(cards, (card) => {
      cardData(card);
    });
  }

function mockData(card) {
  
   var setInt;

    function caseOne(card, callBackOne) {
      callBackOne(card);
    }

    function caseTwo(card, callBackTwo) {
      callBackTwo(card);
    }
    
    // SetInterval function
    function callBackOne(card) {
      setInt = setInterval(function () {
        var currentDate = Date.now();
        var val = String(currentDate).substr(8, 2);
      }, 1000);
    }
    //clearInterval
    function callBackTwo(card) {
      clearInterval(setInt);
    }
   
   
  switch(card) 
    {
     case "c1":
     return {
       target: card,
       value: caseOne(card, callBackOne)
     }
     case "c2":
     return {
       target: card,
       value: caseTwo(card, callBackTwo)
     }
     }
     }
     
   function Callback(value, callback) {
    callback(value);
    }
 
  function myCard(card) {
    Callback(mockData(card), function (data) {
      console.log(data);
      var target = document.getElementById(data.target);
      var content = target.getElementsByClassName('content')[0];
      content.innerHTML = data.value;
    });
  }
 
 
  //Onload function
 window.onload = function () {
 allCardData();
 };

I need a dynamic data every 2S in card1 and a static data Which clears the dynamic value in card2.

But, it is not working.

Since, callback function expects return, When I pass the function mockData to the callback. It is not working as expected.

Could someone please help me to start the dynamic data in card1 and clear the data in card2.?

Many thanks.

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

0

This is what the code does:

  • Calling allCardData() for window.onload
  • allCardData() calls cardData() for each card found with the card's id
  • cardData() calls myCard() in an intermediate step
  • myCard() makes Callback call mockData() for the card
  • mockData() calls caseOne() for card c1 and caseTwo() for card c2
  • caseOne() sets a 2 second interval
  • caseTwo() cancels the interval

There is no time between calling caseOne() and caseTwo(). They are called after each other with no time in between. This means the timer is cancelled immediately after it is initialized. No time for the 2 second timer to do anything.

Suggested solution to change caseTwo() to only clear timer after a certain condition has passed. Otherwise the interval will never start.
You may want to google about async/await, you may need to change your code in other parts:

  async function caseTwo(card) {
    // asynchronously wait, stopping this function until the value is known
    var value = await getValueTwoFromSomewhere();
    
    clearInterval(setInt);
    return value;
  }

Otherwise the code would need to be rewritten to something different.
Maybe you want to rethink your solution and post it again as another question.

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