Animations under single threaded JavaScript

前端 未结 4 692
既然无缘
既然无缘 2021-02-14 18:04

JavaScript is a single threaded language and therefore it executes one command at a time. Asynchronous programming is being implemented via Web APIs (DOM fo

4条回答
  •  走了就别回头了
    2021-02-14 18:35

    Event Loop

    JavaScript uses what is called an event loop. The event loop is like a while(true) loop.

    To simplify it, assume that JavaScript has one gigantic array where it stores all the events. The event loop loops through this event loop, starting from the oldest event to the newest event. That is, JavaScript does something like this:

    while (true) {
         var event = eventsArray.unshift();
    
         if (event) {
           event.process();
         }
    }
    

    If, during the processing of the event (event.process), a new event is fired (let's call this eventA), the new event is saved in the eventsArray and execution of the current continues. When the current event is done processing, the next event is processed and so on, until we reach eventA.

    Coming to your sample code,

    $('#mybox').hide(17000);
    console.log('Previous command has not yet terminated!');
    

    When the first line is executed, an event listener is created and a timer is started. Say jQuery uses 100ms frames. A timer of 100ms is created, with a callback function. The timer starts running in the background (the implementation of this is internal to the browser), while the control is given back to your script. So, while the timer is running in the background, your script continues to line two. After 100ms, the timer finishes, and fires an event. This event is saved in the eventsArray above, it does not get executed immediately. Once your code is done executing, JavaScript checks the eventsArray and sees that there is one new event, and then executes it.

    The event is then run, and your div or whatever element it is moves a few pixels, and a new 100ms timer starts.

    Please note that this is a simplification, not the actual working of the whole thing. There are a few complications to the whole thing, like the stack and all. Please see the MDN article here for more info.

提交回复
热议问题