Kendall Kelly
Kendall Kelly

Reputation: 121

How to iterate over each item in a loop with a delay in node js

I am working a on a twitter monitor in node, and I each time I send a request to the twitter api, I loop through the array of twitter api keys, I want to have a 3 second delay between each loop iteration,

i tried using setTimeout but that did not work

const apiarray =  [new twit({
    consumer_key: '5435435435435',
    consumer_secret: '5435435345345',
    access_token: 'tewrt43543354355453',
    access_token_secret: '48239478234923047324734' 

    }),
    new twit({
    consumer_key: '3213235543254343534543',
    consumer_secret: '8768768768678768',
    access_token: '765474657765756745',
    access_token_secret: '65434563654634643654643'
})]


let counter = 0
let tweet_stay = []
let tweet_info = () => { 
    apiarray.forEach(function (item) {
        item.get('lists/statuses', {slug: 'slughere', owner_screen_name: 'namehere', count: 1, include_rts: false}, (err, data, response) => {
            counter ++
            console.log(counter)
            if (counter == 1) {
                tweet_stay.push(data[0].id)
                console.log('tweet ID added')
            }
       }
}
setInterval(tweet_info, 3000)

Upvotes: 0

Views: 115

Answers (1)

djfdev
djfdev

Reputation: 6037

You'll need to wrap the timer in a promise, so that it can be awaited. Then, you can make tweet_info an async function and use the wrapped timer to delay iterations.

Note that you'll have to use a for loop instead of forEach:

let delay = ms => {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

let tweet_info = async () => {
  for (let i = 0; i < apiarray.length; i++) {
    await delay(3000)
    // do something else here
  }
}

Upvotes: 1

Related Questions