Home > database >  How can I use setInterval and clearInterval in two different function?
How can I use setInterval and clearInterval in two different function?

Time:12-27

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.

CodePudding user response:

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>

CodePudding user response:

Change it to

const myInterval = setInterval(getData, 5000);

From the https://developer.mozilla.org/en-US/docs/Web/API/setInterval:

The returned ... is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to clearInterval() to cancel the interval.

So, in your case, the returned value is not what is returned from setInterval itself, yet a different function.

Note: the answer is on assumption you are using myInterval in the same scope where you set and clear it.

  • Related