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

183
Visualizações
How can I use setInterval and clearInterval in two different function?

What am I missing here? I can call myInterval function, but I can't stop it with clearInterval.

const getData = () => {
db.transaction((tx) => {
  tx.executeSql(
    "SELECT * FROM itinerary_details",
    [],
    (tx, results) => {
      var data = [];
      for (let i = 0; i < results.rows.length; ++i)
        data.push(results.rows.item(i));
      console.log(data) 
    }
  )
})
}

So I am trying to have 2 buttons with 2 different function that I can call:

to start:

const myInterval = () => {
   setInterval(getData, 5000)
}

to end the setInterval:

const stopData = () => {
   clearInterval(myInterval)
   console.log("STOPED")
}

I can see the console.log, but not calling the function myInterval

Please help.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You need to store the interval ID somwhere and when clearing, you need this one.

let intervalID = null; // global

const
    startData = () => {
        if (intervalID !== null) return;
        intervalID = setInterval(getData, 5000);
    },
    stopData = () => {
        if (intervalID === null) return;
        clearInterval(intervalID);
        intervalID = null;
        console.log("STOPED");
    },
    getData = () => console.log(new Date().toISOString() + ': getData');

document.getElementById('start').addEventListener('click', startData);
document.getElementById('stop').addEventListener('click', stopData);
<button id="start">Start</button> <button id="stop">Stop</button>

about 4 years ago · Santiago Trujillo 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