Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

run function periodically with setInterval

const useInterval = (callback, interval, immediate) => {
  const ref = useRef();

  // keep reference to callback without restarting the interval
  useEffect(() => {
    ref.current = callback;
  }, [callback]);

  useEffect(() => {
    // when this flag is set, closure is stale
    let cancelled = false;

    // wrap callback to pass isCancelled getter as an argument
    const fn = () => {
      ref.current(() => cancelled);
    };

    // set interval and run immediately if requested
    const id = setInterval(fn, interval);
    if (immediate) fn();

    // define cleanup logic that runs
    // when component is unmounting
    // or when or interval or immediate have changed
    return () => {
      cancelled = true;
      clearInterval(id);
    };
  }, [interval, immediate]);
};

//Then you can use the hook like this:

const [temperature, setTemperature] = useState();

useInterval(async (isCancelled) => {
  try {
    const response = await fetch('urlToWeatherData');
    // check for cancellation after each await
    // to prevent further action on a stale closure
    if (isCancelled()) return;

    if (response.status !== 200) {
      // throw here to handle errors in catch block
      throw new Error(response.statusText);
    }

    const [{ temperature }] = await response.json();
    if (isCancelled()) return;

    console.log(temperature);
    setTemperature(temperature);
  } catch (err) {
    console.log('Fetch Error:', err);
  }
}, 15000, true);
Comment

PREVIOUS NEXT
Code Example
Javascript :: pimcore 
Javascript :: shopify liquid logic 
Javascript :: leaflet limit map panning 
Javascript :: EFSavechanges 
Javascript :: express socket 
Javascript :: react native app exit 
Javascript :: regex concatenazione 
Javascript :: javascript undefined used with number, boolean or null 
Javascript :: expo create react native app command 
Javascript :: javascript + Operator with Numbers 
Javascript :: javascript Multiline Strings Using Template Literals 
Javascript :: javascript for...of with Generators 
Javascript :: javascript Using yield to Pause Execution 
Javascript :: ajax introduction 
Javascript :: set up express server and scraper 
Javascript :: code grepper temp email number and password 
Javascript :: TypeError: _enzymeAdapterReact.EnzymeAdapter is not a constructor 
Javascript :: alternative for react-tilt 
Javascript :: phaser place items on circle 
Javascript :: phaser hide animation on complete 
Javascript :: mui adding eye toggle at password field 
Javascript :: when end sound show alert 
Javascript :: Call this API in order to fetch the user data. API: https://jsonplaceholder.typicode.com/users. 
Javascript :: enum jpa jsf jakarta9 
Javascript :: split array by character javascript 
Javascript :: forms in angular 
Javascript :: how to assign an rest operator in javascript 
Javascript :: javascript extract array from object 
Javascript :: react sass 
Javascript :: getDownload url in firebase 
ADD CONTENT
Topic
Content
Source link
Name
9+1 =