LearnFrenzy
Sign in Take a free test

Async/Await · Async/Await Coding Problems · Question 9

A typing effect with await in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Build a "typing" effect that reveals a message one word at a time with a small pause between words, using a for…of loop and await, and then prints how many steps it took.

Solution
main.js
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function typeOut(message, pauseMs) {
  const words = message.split(" ");
  let shown = "";
  for (const word of words) {
    shown = shown ? `${shown} ${word}` : word;
    console.log(shown);
    await sleep(pauseMs);
  }
  return words.length;
}

(async () => {
  const steps = await typeOut("Practice makes you perfect", 5);
  console.log(`(${steps} steps)`);
})();

Output Verified by running it on Node.js

Practice
Practice makes
Practice makes you
Practice makes you perfect
(4 steps)

await inside for…of pauses between iterations, which is exactly what animations, rate-limited requests and step-by-step demos need.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links