简体   繁体   English

如何停止 setInterval?

[英]How can I stop setInterval?

I'm trying to clear setInterval with calling clearInterval.我正在尝试通过调用 clearInterval 来清除 setInterval。 however, i call setInterval function inside function.但是,我在函数内部调用 setInterval 函数。 So I'd like to trigger the parameter in the setInterval by clearInterval, But i do not know how to get reach this thing.所以我想通过clearInterval触发setInterval中的参数,但我不知道如何到达这个东西。 And what i say is confusing so I just want to show u the code :我所说的令人困惑,所以我只想向您展示代码:

 function getAPI() { const polling = () => { if (convert !== undefined) { axios .post("/realtime", { GET_API_URL: convert.GET_API_URL, Headers1_key: convert.Headers1_key, Headers1_Value: convert.Headers1_Value, Headers2_key: convert.Headers2_key, Headers2_Value: convert.Headers2_Value, Headers3_key: convert.Headers3_key, Headers3_Value: convert.Headers3_Value, }) .then(response => { setRandom(response.data); }) .catch(error => { console.log(error); }); } else { alert("try again."); } }; setInterval(polling, convert.API_Read_Speed); } const init = () => { clearInterval(polling); // i want to call polling and i want to stop the axios posting };

according to your comment seems like you need to stop the polling in react.根据您的评论,您似乎需要停止投票以做出反应。 you can use the useRef hook to keep the reference of the interval and clear it whenever you like.你可以使用useRef钩子来保持区间的引用并在你喜欢的时候清除它。

 useEffect(() => {
  interval.current = setInterval(() => {
    ...
  }, ms)

 }, [input]);

 const closeConnection = () => {
  clearInterval(interval.current);

 }

You can store setInterval inside a variable and access it like that.您可以将setInterval存储在变量中并像这样访问它。
Example:例子:

let interval;

function foo() {
   interval = setInterval(() => {
      ...
   }, ms)
}

function bar() {
   clearInterval(interval);
}

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

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