javascript – using await to make sleep

In old day, when using javascript to create timer,

setInterval or setTimeout are standard function to implement
A few other way to do is using third-party npm library.
or even calling c++ as native timer.

with ES2016, await and asyn keyword has been introducted into.
Here is example.

1
2
3
4
5
6
7
8
9
10
11
12
 
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
 
async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two second later');
}
 
demo();