公开要从外部访问的函数引用

Expose function reference to be accessed from outside

我有这段代码,我在其中添加按钮点击侦听器以调用我的 startTempMonit 函数

$(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;
}

我想知道如何在 startTempMonit 中公开返回的 const Interval,以便在我单击另一个按钮 (#buttonStopTemp) 时能够清除它。

我也试过在最外面的范围内定义 const inter;,我不喜欢这样,但它也不起作用。

你必须初始化一个常量。相反,用 var:

声明 inter

$(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>