获取 setInterval javaScript 中使用的计数器的当前值

Getting the current value of a counter used in setInterval javaScript

假设我定义了以下函数

export const startMoving = () => {
    let counter = 0;
    var intervalId = setInterval(() => {
        // Do something…
        counter++;
    }, 1000);
    return intervalId;
};

虽然在函数中用let定义了'counter',但是可以用,但是我的问题是:如何在一段时间后得到'counter'的值?

拉斐尔

Return不仅是区间ID,还有一个函数表示returns当前值counter.

const startMoving = () => {
    let counter = 0;
    var intervalId = setInterval(() => {
        // Do something…
        counter++;
    }, 1000);
    return [intervalId, () => counter];
};


const [intervalId, getCounter] = startMoving();
document.body.addEventListener('click', () => document.body.textContent = getCounter());
click here