宏任务和微任务注意点

<script>
        document.body.style.background = 'red';
        console.log(1)
        Promise.resolve().then(()=>{
            console.log(2)
            document.body.style.background = 'yellow';
        })
        console.log(3);
</script>

这个出来是不会有红色的,因为promise是微任务,直接gui渲染出来就是黄色了。如果promise换成setTimeout((),0)就是红到黄

// es6内部是一个微任务
Promise.resolve().then(()=>{
    console.log('1');
    setTimeout(()=>{
        console.log('4');
        
    },0)
    
})
setTimeout(()=>{
    console.log('2')
    Promise.resolve().then(()=>{
        console.log(('3'));
        
    })
},0)

//整个浏览器运行的原理是1.微任务[promise] 宏任务[setTimeout]2.走微任务,又把新的setTimeout放到宏任务队列3.取出第一个宏任务,也就是最开始的那个setTimeout.(当然如果设置时间就是哪个先到先执行)
原文地址:https://www.cnblogs.com/TTblog5/p/13081607.html