【问题标题】:clearInterval() fails to stop an interval running on a timerclearInterval() 无法停止在计时器上运行的间隔
【发布时间】:2023-02-09 01:22:59
【问题描述】:

第一次使用 clearInterval() 查看其他示例和间隔文档,这似乎是停止间隔的方法。不知道我错过了什么。

目的是在 currentStop 道具更新时终止计时器。

import React, { useEffect, useState } from 'react';

type Props = {
  stopNumber: number;
  currentStop: number;
};

const timerComponent = ({ stopNumber, currentStop }: Props) => {
  let interval: NodeJS.Timer;

  // Update elapsed on a timer
  useEffect(() => {
    if (stopNumber === currentStop) {
      interval = setInterval(() => {
        console.log('timer is running');
      }, 3000);

      // Clear interval on unmount
      return () => clearInterval(interval);
    }
  }, []);

  // Clear timers that were running
  useEffect(() => {
    if (stopNumber !== currentStop) {
      clearInterval(interval);
    }
  }, [currentStop]);
};

【问题讨论】:

标签: javascript reactjs setinterval


【解决方案1】:

将 intervalId 存储在 ref 上

const timerComponent = ({ stopNumber, currentStop }: Props) => {
  const intervalRef = useRef({
    intervalId: 0
  })

  // Update elapsed on a timer
  useEffect(() => {
    if (stopNumber === currentStop) {
      intervalRef.current.intervalId = setInterval(() => {
        console.log('timer is running');
      }, 3000);

      // Clear interval on unmount
      return () => clearInterval(intervalRef.current.intervalId);
    }
  }, []);

  // Clear timers that were running
  useEffect(() => {
    if (stopNumber !== currentStop) {
      clearInterval(intervalRef.current.intervalId);
    }
  }, [currentStop]);
};

【讨论】:

    【解决方案2】:

    使用 ref 来存储间隔 id。

    let interval = useRef();
    // to start the setInterval:
    interval.current = setInterval(...);
    // to stop the setInterval:
    clearInterval(interval.current);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      相关资源
      最近更新 更多