Search code examples
reactjsreact-hooksuse-effect

How to call a method with a delay?


In useeffect, I want to call a service several times..But because the service has a rate limit, I can not do this at the same time .How can I set the request to be sent to the api every two seconds? This is what I have :

 useEffect(() => {
         getRegionsByParentId(null ,regionType.Continent);
         getRegionsByParentId(ContinentId ,regionType.Country);
         getRegionsByParentId(CountryId,regionType.Province);
         getRegionsByParentId(ProvinceId ,regionType.City);
         getRegionsByParentId(CityId ,regionType.Section);
   
  }, [props.data]);

What I want to do is to call getRegionsByParentId(null ,regionType.Continent);first, then getRegionsByParentId(ContinentId ,regionType.Country);after two seconds, and so on.


Solution

  • You can try this using setTimeout, a for loop and computed property names:

    let multiArray = [[null, 'Continent' ],
    [ ContinentId  , 'Country' ],
    [ CountryId , 'Province'],
    [ ProvinceId  , 'City' ],
    [ CityId  , 'Section' ]
    ];
    
    for(let i = 0 ; i <  multiArray.length; i++){
    setTimeout(()=> { getRegionsByParentId(multiArray[i][0], regionType[multiArray[i][1]]); },i*2000);
    }