One job at a time

Run some slow jobs strictly one after another.

What to build

An async function that waits for each job to finish before it starts the next.

Requirements

  • Each input line is a delay in milliseconds, then a space, then a word.
  • For each line, wait for the delay and then print the word.
  • A job must not start until the one before it has finished, so the words print in input order, whatever the delays are.
  • After the last job, print done.

Input

Several lines: DELAY WORD.

Output

One word per line, then done.

Constraints

There are from 1 to 20 lines, and each delay is from 0 to 1000.

Example

Input:

300 a
100 b

Output:

a
b
done

Why it works

await inside a loop pauses the function on each pass, so the second job is not even started until the first has finished. That is what you need when each step depends on the one before.

Examples

Example 1 · Input
300 a
100 b
Expected output
a
b
done
Example 2 · Input
0 only
Expected output
only
done

Hints

Hint 1

wait(ms) is a promise that settles after that many milliseconds.

Hint 2

Inside an async function, a for...of loop can await on each pass.

Hint 3

Each job then starts only after the one before it has finished.

Solution

Show one correct solution (try it yourself first)
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function main() {
  let line = prompt();
  while (line !== null) {
    const [delay, word] = line.split(" ");
    await wait(Number(delay));
    console.log(word);
    line = prompt();
  }
  console.log("done");
}

main();

Lesson: Asynchronous JavaScript: event loop, promises, async/await →