When is JavaScript synchronous?

前端 未结 7 1999
孤独总比滥情好
孤独总比滥情好 2020-11-22 03:48

I have been under the impression for that JavaScript was always asynchronous. However, I have learned that there are situations where it is not (ie DOM manipulations). Is

7条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:49

    Is synchronous on all cases.

    Example of blocking thread with Promises:

      const test = () => new Promise((result, reject) => {
        const time = new Date().getTime() + (3 * 1000);
    
        console.info('Test start...');
    
        while (new Date().getTime() < time) {
          // Waiting...
        }
    
        console.info('Test finish...');
      });
    
      test()
        .then(() => console.info('Then'))
        .finally(() => console.info('Finally'));
    
      console.info('Finish!');
    

    The output will be:

    Test start...
    Test finish...
    Finish!
    

提交回复
热议问题