Timeout for an async loop: if loop do not finishes before timeout, it will break anyway.

I don't see any blatant issues with that idea, so it could work.

Except for the fact that the JavaScript committee doesn't want to introduce any sort of timers into the spec. setTImeout is not part of JavaScript, it's just an extra function that most platforms provide. I'm not completely sure on the reasons behind this decision (I did ask about it over here once, if you care to peek at that thread).

Perhaps if a proposal comes forth that brings a strong enough motivation with it to include timers in the syntax, then maybe committee members would rethink their stance about not having timers in native JavaScript, but I don't know if that'll ever happen (I don't know how much committee members care about this current stance).

Another option would be to make this syntax not use timeouts directly, rather, it can use accept sort of cancelation logic (via a cancel token). Then, browser APIs could provide a shorthand method to create timeout cancel tokens. For example:

// timeout() comes from a browser API.
// It accepts a ms parameter and returns a cancel token
await[timeout(1000)] someAsyncTask()

// You get additional benefits, like making multiple async tasks all
// be required to executed in the same time.
// This wouldn't otherwise be possible with the current await[] syntax.
function doManyTasks(timeout) {
  const token = timeout(timeout)
  await[token] task1()
  await[token] task2()
  await[token] task3()
}

This would just be syntax shorthand for a Promise.race().

1 Like