Call a Function Inside an Array with async/wait in JavaScript

September 2025

I'm working on alice.alanwsmith.com. It's a experiment where each letter of the alphabet gets its own styling that changes over time.

Dealing with the timing took a bit to figure out. I've got an array that holds collection of function that do the updates. Each one needs delays in various places.

This is the class based version of the solution I'm using:

Class Based

Output

Waiting for Class

HTML

<div class="targetForClass">Waiting for Class<div>
JavaScript
class Widget {
  constructor() {
    this.counter = 0;
    this.sleepTimeMs = 2000;
    this.collection = [
      this.updateText.bind(
        this, `Class sleeping for ${this.sleepTimeMs}ms...`),
      this.sleep.bind(this),
      this.updateText.bind(
        this, "Class done sleeping."
      ),
    ];
  }

  updateText(text) {
    const el = document.querySelector(".targetForClass");
    el.innerHTML = text;
  }

  sleep() {
    return new Promise(
      (resolve) => setTimeout(resolve, this.sleepTimeMs)
    );
  }

  async run() {
    for (let item of this.collection) {
      await item();
    }
  }
}

const w = new Widget();
w.run()

Function Based

And here's a function based approach when working outside of a class:

Output

Waiting for Functions

HTML

<div class="targetForFunctions">Waiting for Functions</div>
JavaScript
const collection = [
  setContent.bind(null, "Functions sleeping 2 seconds"),
  sleep.bind(null, 2000),
  setContent.bind(null, "Functions done sleeping"),
];

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function setContent(value) {
  const el = document.querySelector(".targetForFunctions");
  el.innerHTML = value;
}

async function runCollection() {
  for (let item of collection) {
    await item();
  }
}

runCollection();
end of line

Endnotes

Replacing the for (let item of ARRAY); look with a ARRAY.forEach((item) => {});javascript won't work. The functions will all fire but the await won't trigger so they go by without a delay.