简体   繁体   English

按住按钮时显示倒计时然后显示警报

[英]Show countdown when holding button then show alert

I'm trying to create a button, which when hold shows a countdown of 3 seconds, if kept on hold for 3 seconds it shows an alert, but for some reason the countdown doesn't reset properly AND the alert fires up anyway, at every click (after the timeout)我正在尝试创建一个按钮,当按住时显示 3 秒的倒计时,如果保持 3 秒它会显示警报,但由于某种原因倒计时没有正确重置并且警报无论如何都会触发,在每次点击(超时后)

my code is:我的代码是:

const [showCountdown, setShowCountdown] = useState(false)
const [holdTimer, setHoldTimer] = useState(3)

var timer = 0, interval;
const refreshDown = () => {
    setShowCountdown(true)
    interval = setInterval(function(){       
        setHoldTimer((t) => t - 1)
    },1000);
    timer = setTimeout(function(){
        if (confirm('Refresh page?')){
            window.location.reload()
        }
    },3000)
}
const refreshUp = () => {
    clearTimeout(timer)
    clearInterval(interval)
    setShowCountdown(false)
    setHoldTimer(3)
}

my html button has these two:我的 html 按钮有这两个:

<svg onMouseDown={() => refreshDown()} onMouseUp={() => refreshUp()}>
  ...
</svg>

Have you tried with useRef ?您是否尝试过useRef

const timer = useRef();
  const interval = useRef();
  const refreshDown = () => {
    setShowCountdown(true);
    interval.current = setInterval(function () {
      setHoldTimer((t) => t - 1);
    }, 1000);
    timer.current = setTimeout(function () {
      if (confirm("Refresh page?")) {
        window.location.reload();
      }
    }, 3000);
  };
  const refreshUp = () => {
    clearTimeout(timer.current);
    clearInterval(interval.current);
    setShowCountdown(false);
    setHoldTimer(3);
  };

React component is rerendered each time state or props are changed.每次 state 或更改道具时,都会重新渲染 React 组件。 When setHoldTimer is executed, it changes the state. It causes reexecuttion of component's code, so local variables “timer” and “interval” are declared again with values “0” and “undefined”, also new “refreshUp” function is created referencing new “timer” and “interval”.当 setHoldTimer 被执行时,它改变了 state。它导致组件代码的重新执行,所以局部变量“timer”和“interval”被再次声明为值“0”和“undefined”,同时新的“refreshUp”function 被创建引用新的“计时器”和“间隔”。 When you release the mouse, new “refreshUp” is called, interval and timeout are not cleared.当你释放鼠标时,调用新的“refreshUp”,interval 和 timeout 不会被清除。

Try to define timer and interval as a state or with “useRef”.尝试将计时器和间隔定义为 state 或使用“useRef”。 This way they will not be redefined during rerender.这样它们就不会在重新渲染期间被重新定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM