1

Lets say I have a function called getData()

const getData = (id) => {
  doSomeStaff ... 
}

Then I have another function as above

const callData = () => {
  var idFromDatabases = ...
  idFromDatabases.forEach(item => {
    getData(item.id)
  }) 
}

What I am trying to do is to delay each call of getData function. The easy way would be to setTimeout inside the callData function like above

const callData = () => {
  var idFromDatabases = ...
  idFromDatabases.forEach(item => {
    setTimeout(getData(item.id), 3000)
  }) 
}

But I want somehow the delay to happen into getData. Sow the basic idea is, from wherever getData is called, I want a time interval between calls. Any ideas?

  • Does this answer your question? [Javascript: Loop through Array with Delay](https://stackoverflow.com/questions/30865456/javascript-loop-through-array-with-delay) – Harun Yilmaz Jul 09 '20 at 09:14
  • Also: https://stackoverflow.com/questions/10965285/loop-over-array-but-with-a-time-delay/10965300 – Harun Yilmaz Jul 09 '20 at 09:14
  • 1
    For anything async, have a look at promises or even better async / await.. – Keith Jul 09 '20 at 09:17
  • @HarunYilmaz no because as I said I need the function delay to happen in getData, not in callData – Nikos Chatzivasileiadis Jul 09 '20 at 09:19
  • If I look at the code above. You want the delay becasue you want the getData call to fired sequentially for each item i.e. when first item has returned call the second one right. If that is correct async/await is your best bet. – Manish Jul 09 '20 at 09:26
  • @Manish Not exactly, actually inside getData I send some request into google API, and I want to prevent spamming . Thank you all in advance guys – Nikos Chatzivasileiadis Jul 09 '20 at 09:28

1 Answers1

2

You can do this like that using async/await:

const data = ["A", "H", "O", "y", "!", "!!"]

const sleeper = (ms) => new Promise(resolve => setTimeout(resolve, ms))

const sequence = async (data, callback, ms) => {
  for(const item of data) {
    callback(item)
    await sleeper(ms)
  }
}

const getData = (id) => {
  console.log("GET: " + id)
}

const callData = () => {
  console.log("before sequence")
  sequence(data, getData, 500)
  console.log("after sequence")
}

callData()
TeWu
  • 5,928
  • 2
  • 22
  • 36