简体   繁体   English

ReactJS + Typescript 中的条件 setInterval 和 clearInterval

[英]Conditional setInterval & clearInterval in ReactJS + Typescript

In single page web app, city's map rendered with traffic layer.在单页 web 应用程序中,城市的 map 使用流量层渲染。
Currently, working on a live mode switch, which if ON should update the traffic layer on map every 5 minutes.目前,正在使用实时模式开关,如果打开,则应每 5 分钟更新一次 map 上的流量层。
When live mode is switched off, the 5 minute timer should go off.当直播模式关闭时,5 分钟定时器应 go 关闭。

For this requirement, got hints for two options from few blogs & posts.对于这个要求,从几个博客和帖子中得到了两个选项的提示。
1. Javascript methods: setInterval and clearInterval 1. Javascript 方法:setInterval 和 clearInterval
2. Use of web sockets 2. web sockets的使用

Since this web app has only couple of users besides lack of knowledge for web sockets, decided to go with the first option.由于这个 web 应用程序除了缺乏对 web sockets 的知识外,只有几个用户,所以决定使用第一个选项 Z34D1F91FB12E518B8567A。 However, faced difficulty in successful execution of clearInterval() when switch goes to off mode.但是,当开关进入关闭模式时,在成功执行 clearInterval() 时遇到困难。
In the code below, 'timeout' value passed to clearInterval is always undefined.在下面的代码中,传递给 clearInterval 的“超时”值始终未定义。

const handleOkBtnClick = (): void => {
    let timeout;
    if(live){
          timeout = setInterval(updateFilter, 60000);
          console.log('live ON == '+ timeout); // prints number like 89 or 146
        }else{
          console.log('live Off == '+ timeout); //always prints 'undefined' 
          clearInterval(timeout);           
        }
    }
}

It looks like conditional execution of setInterval and clearInterval isn't an option.看起来 setInterval 和 clearInterval 的条件执行不是一个选项。
Jumping in to javascript development after a decade, What am I missing?十年后跳入 javascript 开发,我错过了什么?
Any suggestion for alternative approach will be appriciated.任何有关替代方法的建议都将被采纳。
Using ReactJS v16.11, Typescript v3.7使用 ReactJS v16.11、Typescript v3.7

The issue here is that timeout variable is defined within handleOkBtnClick so whenever this function is called, the timeout value is reset to undefined and if live is true, its set to timerId这里的问题是timeout变量是在handleOkBtnClick中定义的,因此每当调用此 function 时,超时值将重置为 undefined,如果 live 为真,则将其设置为 timerId

The solution here is to move the timer to a class variable这里的解决方案是将计时器移动到 class 变量

class TrafficLights extends React.Component {
   timeout = null
   ...
   handleOkBtnClick = (): void => {
    if(live){
          this.timeout = setInterval(updateFilter, 60000);
          console.log('live ON == '+ this.timeout); // prints number like 89 or 146
        }else{
          console.log('live Off == '+ this.timeout); 
          clearInterval(this.timeout);           
        }
     }
   }
   ...
}

Now it looks like you use functional component, so you can store the timeout in a useRef if you use react-hooks现在看起来您使用功能组件,因此如果您使用 react-hooks,则可以将超时存储在useRef

const TrafficLights = () =>   {
   const timeout = useRef<number | null>(null);
    ...
     const handleOkBtnClick = (): void => {
        if(live){
              timeout.current = window.setInterval(updateFilter, 60000);
              console.log('live ON == '+ timeout.current); // prints number like 89 or 146
            }else{
              console.log('live Off == '+ timeout.current); 
              clearInterval(timeout.current);           
            }
         }
       }
      ...
  }
const [timeout, setTimeout] = useState(0);  
const handleOkBtnClick = (): void => {

    if(live){      
      setTimeout(window.setInterval(updateFilter, 60000));
      console.log('timeout == '+ timeout);
    }else{
      console.log('clearInterval == '+ timeout); 
      clearInterval(timeout);          
    }
} 

This code is working without any warning or error.此代码正在运行,没有任何警告或错误。
But, pros and cons of using window.setInterval Vs.但是,使用 window.setInterval Vs 的优缺点。 setInterval if any, should be taken into consideration.如果有 setInterval,则应考虑在内。

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

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