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.
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>