Learn Courses My Dashboard

Delay inside a for loop

Hello there, probably the most of all API providers doesn’t let you get as many as data per minute as you would like. I payed for 100 calls / minute.

How can I delay in a for loop, so when the variable i is a multiple of 100, the for loops stops for 60 SECONDS, and then continue…

static func putStockData_Intraday_InApp() {

for i in Constants.stockSymbol.indices {

        getStockData_Daily(time: Constants.functionDailyAdjusted, symbol: Constants.stockSymbol[i], output_size: "compact")

}

}

// if i is a multiple of 100, stop the for loop, execute getStockData_Daily for each i, wait a minute, repeat until i hits the last indices.

NOTE;
– i represents a stock symbol, for example: MSFT
– Constants.stockSymbol is an array of strings with all the stock symbols I want to publish
– getStockData_Daily() is a function which, for a stock Symbol, (MSFT) get the some data from the api provider regarding this stock, and post it to firebase.

Thank you in advance!

I don’t know if this is useful for your situation or not, but one possibility.

Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.hello), userInfo: nil, repeats: false)
   
   @objc func hello() {
      print("text")
   }
1 Like

I found these examples on the web somewhere a while back.

func functionOne() {
   let delayTime = DispatchTime.now() + 3.0
   print("one")
   DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {
      hello()
   })
}

func hello() {
   print("text")
} functionOne()
1 Like

Yes both of those are ways to create a delay but why would you make an API call inside a loop??

If you create a timer you’re going to lock up the UI (or the app) and the user will be confused why your app stopped responding

Is a separated app from the main app. This app just gets and posts data, the single view element is Text(“Hello!”) that’s it.

I don’t really want to use a for loop and making inside api calls, but do you know any better method to make 7000 api calls with 100 calls/minute limit, automatically and not manually?

Why do you need to make 7000 API calls?

Because I get all stock data and most of the crypto

All stock data, how is this designed?

A user has included 7000 stocks to view?

You shouldn’t really ever need to make 7,000 API calls all at once