Tag Archive for: loop

Asynchronous iteration

Not all loop work the same in JavaScript. If you want an asynchronous loop you cannot use forEach because it will execute each iteration independently, however if you use a for of it will work as expected: it will await until the previous iteration has finished.

async () => {
  for (const e of elements)
    await getCloudData(e)
}

Be aware that in the previous code you will have to wait for each promise to resolve sequentially, which may not be as efficient if all your calls are unrelated. In that scenario, I would recommend you to use Promise.all() that would create parallel connections and will be just as late as the latest response.

async () => {
  let promises = []
  for (const e of elements)
    promises.push(getCloudData(e))
  await Promise.all(promises)
}

Keep in mind that every browser has a specific limit to open parallel connections.

Loop n times without mutable variables

Background responsive loop video

Infinite previous and next selection

Select each element in a selection loop. If you go forward as soon as you finish the list of elements you will start selecting from the beginning and the same if you go in opposite direction.

Don’t forget to use nextElementSibling and previousElementSibling (DOM Elements) instead of nextSibling and previousSibling (DOM Objects). A DOM Object can be anything: comments, insolated text, line breaks, etc. In our example nextSibling would have worked if we had set all our HTML Elements together without anything between then:

<ul><li></li><li></li></ul>