我需要从不同的函数调用 ClearInterval

I need to call ClearInterval from a different function

我正在创建一个倒数计时器,我需要从另一个函数调用 clearInterval,因为我想用两个不同的按钮开始和暂停倒数

这是我的一段代码

const startCountdown = () => {
    const countdown = setInterval(() => {
      setSecondsElapsed(secondsElapsed => secondsElapsed - 1);
    }, 1000);
  };

  const pauseCountdown = () => {
    clearInterval(countdown);
  };

当我按下初始按钮时倒计时开始,但当我按下调用按钮时它不会暂停pauseCountdown()

使用 React 引用来保存计时器引用。设置间隔时,将倒计时参考存储为参考的当前值,并在其他函数中使用参考的当前值清除间隔。

const countDownRef = React.useRef();

const startCountdown = () => {
  countDownRef.current = setInterval(() => {
    setSecondsElapsed(secondsElapsed => secondsElapsed - 1);
  }, 1000);
};

const pauseCountdown = () => {
  clearInterval(countDownRef.current);
};

尝试全局声明倒计时,以便可以从任何函数访问它。我还建议对经常重新定义的事物使用 var 而不是 const,例如可暂停的倒计时循环。

试试这个:

var countdown;

const startCountdown = () => {
    countdown = setInterval(() => {
      setSecondsElapsed(secondsElapsed => secondsElapsed - 1);
    }, 1000);
  };

  const pauseCountdown = () => {
    clearInterval(countdown);
  };

countdown 值在 startCountdown 函数的范围内,因此无法从不在该范围内的 pauseCountdown 函数访问它。

有许多不同的方法可以正确地完成这项工作。我建议您在新抽象的帮助下更加结构化。

我可能会用 Countdown class 来完成这项工作。

class Countdown {
  #sid;
  #start;
  constructor(start){
    this.#start = start;
  }
  startCountdown(){
    this.#sid = setInterval( _ => ( !this.#start && clearInterval(this.#sid)
                                  , console.log(this.#start--)
                                  )
                           , 1000
                           );
  }
  pauseCountdown(){
    clearInterval(this.#sid);
  }
}

var cd = new Countdown(10);
cd.startCountdown();
setTimeout(_ => cd.pauseCountdown(), 5001)
setTimeout(_ => cd.startCountdown(), 10000)

私有 class 字段 #sid#start 分别保留 clearInterval id 和起始值。问题是他们没有暴露在外面的世界。