Is setTimeout required?

后端 未结 2 2012
谎友^
谎友^ 2021-01-23 00:58

I have a question to async, await and setTimeout(). I thought, I use asynchron functions for slow processes. So I tried it with a large loop. On my Computer, it needs few second

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 01:52

    The difference is that this is completely synchronous code:

    return new Promise(resolve => {
        for (let i = 0; i < 4000000000; i++) {};
        resolve('Ready at ' + new Date().toLocaleTimeString('de'));
    });
    

    This statement will block the JavaScript thread and force it to wait until all of those 4 billion iterations have taken place. Then it will move on to the next statement. Since the console.log executes after this, it will not execute until that loop has finished.

    That's why you are seeing a difference.

提交回复
热议问题