美文网首页
Event Loop in Javascript

Event Loop in Javascript

作者: Neiyo | 来源:发表于2016-12-02 09:50 被阅读0次

    I like to record what I learned from technical salon or some thoughts inspired by group discussion. Today's group discussion topic is async and performance in You don’t know JS. Actually, what impressed me a lot is the extension points we discussed about Event Loop in Javascript, below I'd like to record it.

    First,I would like to Introduce a conception

    What is event loop?

    // `eventLoop` is an array that acts as a queue (first-in, first-out)

    var eventLoop = [ ];

    var event;

    // keep going "forever"

    while (true) {

    // perform a "tick"

       if (eventLoop.length > 0) {

          // get the next event in the queue

          event = eventLoop.shift();

          // now, execute the next event

       try {

          event();

       }

       catch (err) {

          reportError(err);

       }

    }

    }

    The above code are easy to understand. Pop every unit in eventLoop out and try to execute. 

    Below is the code need to discuss.

    var res = [];

    // `response(..)` receives array of results from the Ajax call

    function response(data) {

    // let's just do 1000 at a time

    var chunk = data.splice( 0, 1000 );

    // add onto existing `res` array

    res = res.concat(

    // make a new transformed array with all `chunk` values doubled

    chunk.map( function(val){

    return val * 2;

    } )

    );

    // anything left to process?

    if (data.length > 0) {

    // async schedule next batch

    setTimeout( function(){

    response( data );

    }, 0 );

    }

    }

    // ajax(..) is some arbitrary Ajax function given by a library

    ajax( "http://some.url.1", response );

    ajax( "http://some.url.2", response );

    Albert said:“Does these codes will accelerate the speed?If not, why we write code like this?”

    The answer in my mind is to make program smoothly.But Lucky provide a more professional answer.

    We simulated a parallel status which only read 1000 items data when data are too huge and page turn to blocking.

    The key point is what is the core of this fake parallel?

    setTimeout(fn, 0);

    These codes seems simple, execute fn after 0 second.Albert present a core code as below:

    function a(){

       ...

       b();

       ...

    }

    function b(){

       ...

       setTimeout(d, 0);

       c();

       ...

    }

    function c(){

    ...

    }

    function d(){

       ...

    }

    How does Event Loop work?

    What is the running sequence of these codes?

    Please continue to read if your answer is a, b, d, c.

    Obviously, this answer is incorrect, the correct answer is: a, b, c, d

    So what is the running principle of setTimeout(d,0)?  And why single thread javascript can have same function with setTimeout?

    Now we can lead in eventLoop which was mentioned in the beginning.

    Single thread means that all tasks need to queue, one by one.    At 21st century, CPU is more power than before. They can solve plenty of tasks during most of time. IO devices, by contrast, are so slow that CPU need to be idle to wait for them(.e.g ajax actions).

    Designer of Javascript has already realized it,main thread can completely regardless of the IO equipment, hang in this task and run next one.Wait until the IO device returns the results, and then turn around, to carry out the pending mission.

    So, all tasks can be divided into two types, one is the synchronous task, the other is the asynchronous task.Synchronous task refers to the task of queuing in the main thread.Asynchronous task refers to, do not enter the main thread, and into the "task queue" (task queue) task, only the "task queue" notify the main thread, an asynchronous task can be implemented, the task will enter the main thread of execution.

    Synchronous task will be run only when previous on is finished.

    ———translated from the blog of Mr. Ruan Yifeng《Explain the operation mechanism of Javascript: Event Loop》

    Back to see the above section of code. Fn a() is running and be added into stack until fn b appear.At this time, something associated with a() like context, pointer and so on will be pushed into heap.The same thing occurred on b() and c().The only question is when will the method in b() setTimeout be called?

    setTimeout will cause d() be pushed into eventLoop when it is running.

    When the entire stack and heap is empty, that is, the main thread is idle, it will start to view the eventLoop, compared to each of the event time stamp,

    If the timestamp expires, call the event. If event does not meet the conditions of the start of the next process.

    Above is my own understanding and some thinking for the contents of Albert told today.

    相关文章

      网友评论

          本文标题:Event Loop in Javascript

          本文链接:https://www.haomeiwen.com/subject/asifmttx.html