I have this code, where I add my button click listeners to call my startTempMonit function
$(function () {
const inter;
$("#buttonStartTemp").click(function () {
inter = startTempMonit(onFetchCallback.store);
});
$("#buttonStopTemp").click(function () {
clearInterval(inter); //inter is undefined
});
});
function startTempMonit(callback) {
var time = 0;
const Interval= setInterval(function () {
...
}, 500);
return Interval;
}
I would like o to know how to expose the returned const Interval in the startTempMonit so as to be able to clear it when I click the other button (#buttonStopTemp).
I also tried defining const inter; in the outest scope, which I would not like, but its does not work either.
You have to initialize a constant. Instead, declare inter with var:
$(function () {
var inter;
$("#buttonStartTemp").click(function () {
inter = startTempMonit(()=>console.log(1));
});
$("#buttonStopTemp").click(function () {
clearInterval(inter);
});
});
function startTempMonit(callback) {
var time = 0;
const Interval= setInterval(callback, 500);
return Interval;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="buttonStartTemp">Start</button>
<button id="buttonStopTemp">Stop</button>