Skip to content

Instantly share code, notes, and snippets.

@zignd
Forked from danharper/1-sleep-es7.js
Created January 23, 2017 21:15
Show Gist options
  • Select an option

  • Save zignd/8c0e95850158a88f348d07a3af468bf5 to your computer and use it in GitHub Desktop.

Select an option

Save zignd/8c0e95850158a88f348d07a3af468bf5 to your computer and use it in GitHub Desktop.

Revisions

  1. @danharper danharper created this gist Feb 8, 2015.
    10 changes: 10 additions & 0 deletions 1-sleep-es7.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    // ES7, async/await
    function sleep(ms = 0) {
    return new Promise(r => setTimeout(r, ms));
    }

    (async () => {
    console.log('a');
    await sleep(1000);
    console.log('b');
    })()
    21 changes: 21 additions & 0 deletions 2-sleep-es6-promise.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    // ES6, native Promises, arrow functions, default arguments
    function sleep(ms = 0) {
    return new Promise(r => setTimeout(r, ms));
    }

    console.log('a');
    sleep(1000).then(() => {
    console.log('b');
    });

    // or if we were to be strictly identical, an "async" function returns a
    // Promise, so this is more accurate, but the fluff isn't needed for in this case

    (function() {
    return new Promise((resolve, reject) => {
    sleep(1000).then(() => {
    console.log('b');
    resolve();
    });
    });
    })();
    14 changes: 14 additions & 0 deletions 3-sleep-es6-just-promise.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    // ES6, native Promises ONLY
    function sleep(ms) {
    ms = ms || 0;
    return new Promise(function(resolve) {
    setTimeout(resolve, ms);
    });
    }

    (function() {
    console.log('a');
    sleep(1000).then(function() {
    console.log('b');
    });
    })();
    12 changes: 12 additions & 0 deletions 4-sleep-es5.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    // ES5, nothing special
    function sleep(ms, callback) {
    ms = ms || 0;
    setTimeout(callback, ms);
    }

    (function() {
    console.log('a');
    sleep(1000, function() {
    console.log('b');
    });
    })();