Take a look at this piece of javascript
code that runs live in your browser:
async function sleep(ms = 0) {
return new Promise(r => setTimeout(r, ms));
}
async function run() {
console.log("Before: " + (new Date()).toString());
await sleep(3000);
console.log("After: " + (new Date()).toString());
}
run();
Have you noticed something special?
It calls a javascript
function named sleep
that actually sleeps without using any callbacks.
async and await are part of EcmaScript 2017
and are supported only in Chrome 55
, Firefox 52.0
and Opera 42
.
But even if you are currently in a different browser, the above code snippet runs fine because it is transpiled with Babel Standalone.
Go ahead, play with this code snippet, modify it as you wish and it will be reevaluated after 3 seconds of inactivity (or by pressing Ctrl-Enter
).
This interactive code snippet is powered by a tool of mine: the klipse plugin. If you like it, I’d really appreciate your star on github.