Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!