search

Home  >  Q&A  >  body text

javascript - js mechanism problem, should we wait for the main thread to finish executing before executing asynchronously? If the main thread has tens of thousands of lines, or is it context-related?

1. Like the question, I want to ask a question about the js mechanism. Is it possible to wait for the main thread to finish executing before performing asynchronous operations?
2. Detailed explanation of JavaScript running mechanism: Let’s talk about Event Loop again. Most people have read this article. What Ruan Laoshi said is: Only after the main thread completes execution, the task queue will be read.
3. Today I heard the term context, which probably means that an asynchronous operation only waits for the main thread in the same context to complete its execution. without waiting for other context. I've been searching for a long time today, but I haven't found any similar articles. Please give me an answer! !

为情所困为情所困2699 days ago963

reply all(1)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-07-05 11:09:37

    You confused a lot of things, as well as Ruan Yifeng’s article. . . Criticism is reading. . His article. . There are still many misconceptions. .
    The following is an annotation by Pu Ling: you can take a look for reference

    1. Pu Ling annotated version

    2. nodeJS official documentation evenloop process.nextTick timers relationship

    My understanding is that the main thread of node runs thread code. Only file I/O, network I/O, and timer are asynchronous events and will enter the asynchronous queue. Usually the code you write is synchronous.
    For example, if you have Here’s a program

        setTimeout(function(){
            console.log('test');
        },10);//本来应该是10ms后输出test
        
        for(var i=0;i<10000000;i++){
            //但是这个空的for循环执行了50ms
        }
        //for占住了主线程,倒地timer 事件已经到达触发条件,但是主线程被占用
        //不能去请求完成的事件队列。
        //所以test 会在50ms后输出

    As for the concept of context, I don’t understand it thoroughly. I don’t know which one should be included. I hope someone can give me some advice. . Welcome to criticize or criticize, please tell me where I am wrong. . Hey hey

    reply
    0
  • Cancelreply