推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
shuding

JavaScript 一行简易实现 `sleep(1)`

  •  1
     
  •   shuding · Jun 9, 2016 · 4679 views
    This topic created in 3801 days ago, the information mentioned may be changed or developed.

    其实就是常规的 generator 用法,也是 co , koa 的基本原理。
    ……我折腾了一个 57 字符的 简易 实现。

    在 Console 里运行一发试试吧!

    var d=(f,t=f(),r=t.next())=>r.done||setTimeout(d,r.value,f,t); // <- source code
    d(function *() {                                               // <- wrapper
                                                                   // <- magic
      console.log('foo'); // output 'foo'
      yield 1000;         // delay 1 sec
      console.log('bar'); // output 'bar'
      yield 1000;         // delay 1 sec
      console.log('baz'); // output 'baz'
    
    });
    

    详细: https://github.com/quietshu/delay

    11 replies  •  2016-06-10 11:31:21 +08:00
    breeswish
    breeswish
    Jun 9, 2016❤️2
    1
    都上 generator 了,何不 async/await 走起 :-)

    const sleep = (delay) => new Promise(resolve => setTimeout(resolve, delay));

    console.log('foo');
    await sleep(1000);
    console.log('bar');
    await sleep(1000);
    console.log('baz');
    chairuosen
    chairuosen
    Jun 9, 2016❤️5
    2
    function sleep(delay){
    alert( delay + '秒钟之后点一下确定' );
    }
    kzaemrio
    kzaemrio
    Jun 9, 2016
    3
    @chairuosen 棒棒棒
    jinfeng333
    jinfeng333
    Jun 9, 2016
    4
    这是什么飞机? 意义何在?
    lhbc
    lhbc
    Jun 9, 2016 via Android
    5
    @wujunze 为后续性能优化打下坚实基础
    jinfeng333
    jinfeng333
    Jun 9, 2016
    6
    @lhbc 很久木有写 JS 了 JS 快忘光了
    zhuangzhuang1988
    zhuangzhuang1988
    Jun 9, 2016❤️1
    7
    @breeswish 都 async/await 为何不 async computation expressions 走起 :-)

    async {
    println "foo"
    do! Async.Sleep 10000
    println "bar"
    do! Async.Sleep 10000
    .....
    }

    需要使用 http://fsprojects.github.io/Fable/
    zmj1316
    zmj1316
    Jun 9, 2016❤️2
    8
    js 的 异步 有几种写法?
    shuding
    shuding
    OP
    Jun 9, 2016
    9
    @breeswish 还是 async/await 好看!坐等 native support …
    @zhuangzhuang1988 wow 感谢!没接触过 F#,在看官网 sample 中,赞!!
    jasonliao
    jasonliao
    Jun 9, 2016
    10
    @chairuosen 今日最佳
    bramblex
    bramblex
    Jun 10, 2016
    11
    我自己造了一个编译到 JavaScript 的语言 Smooth , https://github.com/bramblex/Smooth

    这种问题在 Smooth 里面实现简直不能太简单了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1716 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 17:19 · PVG 01:19 · LAX 09:19 · JFK 12:19
    ♥ Do have faith in what you're doing.