Use timer to monitor return in react

In React, you can use  setInterval() functions to execute functions every so often. If you need to stop the execution after getting the returned result, you can use  clearInterval() the function to stop the timer.

Here is a sample code that executes  checkData() a function every 2 seconds until  checkData() the function returns a result:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    let timer = setInterval(async function() {
      let result = await checkData(); // 检查数据,如果有结果则返回
      if (result) {
        clearInterval(timer);  // 停止执行
      }
    }, 2000);

    return () => {
      clearInterval(timer); // 组件卸载时停止定时器
    };
  }, []);

  return <div>My Component</div>;
}

async function checkData() {
  // 异步请求数据
  let response = await fetch('https://example.com/data');
  let data = await response.json();

  // 检查数据,如果有结果则返回
  if (data && data.result) {
    return data.result;
  }

  return null;
}

In the above code, we used the useEffect() hook in the MyComponent component to execute the timer. In useEffect(), we define a variable called timer to store the ID of the timer. The setInterval() function executes the incoming asynchronous function every 2 seconds. This function calls the checkData() function to check the data, and calls the clearInterval() function to stop the timer after checking the data result.

It should be noted that setInterval() the function will continue to execute until it is manually stopped. If you need to stop the timer under certain conditions, you can use  clearInterval() a function to stop it manually.

Guess you like

Origin blog.csdn.net/bulucc/article/details/129600546