• 杨学茂
    2019-02-23
    function sleep(duration){
        return new Promise(function(resolve){
            setTimeout(resolve, duration);
        })
    }
    async function changeColor(duration,color){
        document.getElementById("traffic-light").style.background = color;
        await sleep(duration);

    }
    async function main(){
        while(true){
            await changeColor(3000,"green");
            await changeColor(1000, "yellow");
            await changeColor(2000, "red");
        }
    }
    main()
    展开

    作者回复: 这个写的完全挑不出毛病,其它同学可以参考。

     1
     294
  • whatever
    2019-03-02
    https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
    为了更深入的理解宏任务和微任务,读了这篇。感觉文中说的微任务总是先于宏任务会让人产生误解,更准确的说法应该是微任务总会在下一个宏任务之前执行,在本身所属的宏任务结束后立即执行。
     4
     94
  • 无羡
    2019-02-23
    const lightEle = document.getElementById('traffic-light');
    function changeTrafficLight(color, duration) {
      return new Promise(function(resolve, reject) {
        lightEle.style.background = color;
        setTimeout(resolve, duration);
      })
    }

    async function trafficScheduler() {
      await changeTrafficLight('green', 3000);
      await changeTrafficLight('yellow', 1000);
      await changeTrafficLight('red', 2000);
      trafficScheduler();
    }

    trafficScheduler();
    展开

    作者回复: 这个写的不错,不过,既然都用到了await,是不是可以不用递归呢?

     2
     29
  • 奇奇
    2019-02-28
    怎么区分是宿主环境还是js引擎发起的任务呢
    
     20
  • deiphi
    2019-02-26
    // 比较原始的写法
    function color () {
        console.log('green');
        
        setTimeout(() => {
                console.log('yellow');
                
                setTimeout(() => {
                    console.log('red');
                    
                    setTimeout(color, 2000);
                }, 1000)
        }, 3000);
    }
    color();
    展开

    作者回复: 哈哈哈 这个硬核了啊…… 结果倒是对的

    不试试Promise吗? 我讲了这么多呢……

     2
     18
  • 许吉中
    2019-02-24
    async/await函数属于宏观还是微观?

    作者回复: 它产生Promise,当然是微观任务了

    
     7
  • 帅气小熊猫
    2019-03-22
    怎么确定这个微任务属于一个宏任务呢,js主线程跑下来,遇到setTImeout会放到异步队列宏任务中,那下面的遇到的promise怎么判断出它是属于这个宏任务呢?是不是只有这个宏任务没有从异步队列中取出,中间所碰到的所有微任务都属于这个宏任务?
    
     5
  • CaveShao
    2019-05-15
    function func(color, duration) {
            return new Promise(function(resolve, reject) {
                light.style.backgroundColor = color;
                setTimeout(function() {
                    it.next();
                }, duration)
            })
        }

        function* main() {
            while (1) {
                yield func('red',2000);
                yield func('yellow',1000);
                yield func('green',3000);
            }
        }

        var it = main();
        it.next();
    展开
    
     4
  • 周序猿
    2019-02-26
    // 另类的写法
     var lightDiv = document.getElementById('light')
        function wait(seconds){
          return new Promise((resolve)=>{
            setTimeout(resolve,seconds)
          })
        }

        function light(color, waitTime){
          this.color = color
          this.waitTime = waitTime
        }
        light.prototype.run = function(){
          lightDiv.style.backgroundColor = this.color
          return wait(this.waitTime).then(()=>{
            return this.nextLight.run()
          })
        }

        let redLight = new light('red',2000)
        let yellowLight = new light('yellow',1000)
        let greenLight = new light('green',3000)

        redLight.nextLight = greenLight
        yellowLight.nextLight = redLight
        greenLight.nextLight = yellowLight

        redLight.run()
    展开

    作者回复: 额 这个结果是对的 不过封装成这样 合适吗?

    
     4
  • 许童童
    2019-02-23
    async function controlLoop () {
      await changeColor('green', 3000)
      await changeColor('yellow', 1000)
      await changeColor('red', 2000)
      await controlLoop()
    }

    async function changeColor (color, time) {
      console.log(color + ' begin')
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log(color + ' end')
          resolve()
        }, time)
      })
    }

    controlLoop()
    展开

    作者回复: 你这个有点问题,执行多了可能爆栈,改改试试?

     4
     4
  • 拒绝第十七次🤤
    2019-04-10
    let sleep = (color,deep)=>{
          return new Promise(reslove=>{
            setTimeout(()=>reslove(color) ,deep)
          })
        }
        async function changColor (color){
          await sleep ('green',3000),
          await sleep ('yellow',1000)
          await sleep ('red',2000)
        }
        changColor();
    展开
     1
     3
  • 小孔
    2019-04-09
    1. async/await ,遇到await时就会退出执行,我想问下,退出之后是处于等待await执行完再开始之后吗?
    2. 如果promise中产生setTimeout函数,那么在这里的setTimeout是处于微观任务对吗?因为这是js引擎直接发起的?

    作者回复: 1. 对
    2. 还是宏观任务,因为你调用到了引擎以外的API呀

    
     3
  • Geek_e21f0d
    2019-02-26
    let lightStates = [{
            color: 'green',
            duration: 3000
        },
        {
            color: 'yellow',
            duration: 1000
        },
        {
            color: 'red',
            duration: 2000
        }];
        let setLightColorAndVisibleDuration = function(color, duration) {
            //set light color
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve();
                }, duration);
            });
        }
        let startShowLight = async function() {
            let index = 0;
            while(index <= lightStates.length - 1) {
                let nextState = lightStates[index];
                await setLightColorAndVisibleDuration(nextState.color, nextState.duration);
                index++;
            }
            
        };
        startShowLight();
    展开

    作者回复: 封装不是越复杂越好,太复杂了还不如直接setTimeout了

    
     3
  • Jurieo
    2019-02-26
    哈哈,我自己思考的执行顺序是 同步-异步-回调,成功正确输出了老师你上面的各个代码的答案。
    
     3
  • NeverEver
    2019-02-23
    我想到的方法是用Recursion。写一个函数setColor,需要一个参数color,函数里首先把div的backgroundColor设置color,然后用setTimeout来设置下一个颜色,根据传入的color相应更改时间和颜色即可

    作者回复: 代码写写看呀。 动手是收获最大的。

    
     3
  • a小磊。จุ๊บ �...
    2019-04-11
    大佬们我有问题想不明白:
    new Promise(function(resovle, reject) {
            setTimeout(resovle, duration);
          })
    setTimeout(resovle, duration);和setTimeout(() => {resovle()}, duration);两者到底有什么区别,想不明白,求教
    展开
    
     2
  • oillie
    2019-03-02
    一个宏任务包含一个微任务队列?还是一个event loop里只有一个微任务队列,虽然不影响实际效果,但还是想确认下..
    
     2
  • 奥斯特洛夫斯基
    2019-02-26
    同步的代码和setTimeout都是宏任务?

    作者回复: 应该说一个script标签是一个宏任务。

    
     2
  • dellyoung
    2019-09-08
    15行代码最简实现:
    const changeNowColor = (time) => {
        setTimeout(() => {
            switch (document.getElementById('root').style.background) {
                case 'green':
                    document.getElementById('root').style.background = 'yellow';
                    return changeNowColor(1000);
                case 'yellow':
                    document.getElementById('root').style.background = 'red';
                    return changeNowColor(2000);
                case 'red':
                    document.getElementById('root').style.background = 'green';
                    return changeNowColor(3000);
            }
        }, time);
    };
    changeNowColor(3000);
    展开
    
     1
  • Y
    2019-07-10
    function light(duration) {
        return new Promise((resolve) => {
            setTimeout(resolve,duration)
        })
    }

    async function show() {
        console.log("green");
        await light(3000);
        console.log("yellow");
        await light(1000);
        console.log("red");
        await light(2000);
        return true
    }

    async function cycle() {
        while(await show());
    }

    cycle()
    展开
    
     1
我们在线,来聊聊吧