Advertisement
cornford-michael

call interval with set timeout

Mar 4th, 2025
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from "react";
  2. import axios from "axios";
  3.  
  4. function App() {
  5.   const apiCall = async () => {
  6.     try {
  7.       const ping = await axios({
  8.         url: "https://rest.ensembl.org/info/ping?content-type=application/json",
  9.         method: "GET",
  10.         headers: {
  11.           accept: "Application/json",
  12.           "Content-Type": "Application/json",
  13.         },
  14.       });
  15.       return ping.data;
  16.     } catch (error) {
  17.       return error.response;
  18.     }
  19.   };
  20.  
  21.   const myIntervalFunc = () => {
  22.     let myCall = async () => await apiCall();
  23.     let retryNum = 0;
  24.    
  25.     // do you need to call this here?
  26.     // it doesn't seem like this would do anything
  27.     myCall();
  28.  
  29.     // create interval as a named function
  30.     const interval = async () => {
  31.         let intervalCall = await myCall();
  32.        
  33.         // end loop if ping === 2
  34.         if (intervalCall.ping === 2) {
  35.           return;
  36.         }
  37.  
  38.         retryNum++;
  39.         console.log("INTERVAL DATA ", intervalCall);
  40.        
  41.         // you don't need to change the `===` to `>=`
  42.         // I find this is a `safe` way to handle it
  43.         // in case something else increments retryNum
  44.         // beyond 6
  45.         if (retryNum >= 6) {
  46.           return;
  47.         }
  48.  
  49.         // run `interval` again
  50.         setTimeout(interval, 3000);
  51.     };
  52.    
  53.     // call interval
  54.     //  https://stackoverflow.com/questions/67726138/is-there-a-way-to-fetch-data-every-second-in-nextjs-with-getserversideprops
  55.     interval();
  56.   };
  57.  
  58.   return <button onClick={() => myIntervalFunc()}>Make interval call</button>;
  59. }
  60.  
  61. export default App;
Tags: react
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement