Why is clearTimeout not clearing the timeout in this react component?

我只是一个虾纸丫 提交于 2021-01-27 05:40:14

问题


I am attempting to clear a former timeout before initiating a new timeout, because I want messages to display for 4 seconds and disappear UNLESS a new message pops up before the 4 seconds is up. The Problem: Old timeouts are clearing the current message, so clearTimeout() is not working in this component, in this scenario:


  let t; // "t" for "timer"

  const [message, updateMessage] = useState('This message is to appear for 4 seconds. Unless a new message replaces it.');

  function clearLogger() {
    clearTimeout(t);
    t = setTimeout(() => {
      console.log('wiping message');
      updateMessage('');
    }, 4000);
  }

  function initMessage(msg) {
    updateMessage(msg);
    clearLogger();
  }

The funny thing is that this works:

  function clearLogger() {
    t = setTimeout(() => {
      console.log('wiping message');
      updateMessage('');
    }, 4000);
    clearTimeout(t);
  }

...but obviously defeats the purpose, since it just immediately obliterates the timeout. In practice, I should be able to trigger initMessage() every two seconds and never see, "wiping message' logged to the console.


回答1:


The issue is that on every render the value of t is reset to null. Once you call updateMessage, it will trigger a re-render and will lose it's value. Any variables inside a functional react component get reset on every render (just like inside the render function of a class-based component). You need to save away the value of t using setState if you want to preserve the reference so you can call clearInterval.

However, another way to solve it is to promisify setTimeout. By making it a promise, you remove needing t because it won't resolve until setTimeout finishes. Once it's finished, you can updateMessage('') to reset message. This allows avoids the issue that you're having with your reference to t.

clearLogger = () => {
  return new Promise(resolve => setTimeout(() => updateMessage(''), resolve), 5000));
};

const initMessage = async (msg) => {
  updateMessage(msg);
  await clearLogger();
}



回答2:


Try execute set timeout after clearTimeout() completes

clearTimeout(someVariable, function() {    
          t = setTimeout(() => {
      console.log('wiping message');
      updateMessage('');
    }, 4000);

        });

function clearTimeout(param, callback) {
  //`enter code here`do stuff
} 

Or you can use .then() as well.

clearTimeout(param).then(function(){
     t = setTimeout(() => {
          console.log('wiping message');
          updateMessage('');
        }, 4000);
});


来源:https://stackoverflow.com/questions/57995978/why-is-cleartimeout-not-clearing-the-timeout-in-this-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!