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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!