Deep understanding of JavaScript operating mechanism __java

Source: Internet
Author: User
Tags setinterval
deep understanding of JavaScript operating mechanism PrefaceThis article is written in the training for the new team, so in fact, the audience is a small partner who does not understand or understand the operating mechanism of JavaScript。 In other words, the real principle is not exactly the same as the one described in this article, like a high school textbook and a college textbook, a college teacher will tell you that something in high school is a conclusion in some ideal situation. The purpose of this article is to hope that you can read JavaScript on the operating mechanism of a more intuitive and faster understanding, but more importantly, their Hands-on Practice, only practice can truly discover problems and get promoted:) Received your support and feedback, thank you very much:

To understand the operating mechanism of JavaScript, we need to understand the following points: JavaScript single-threaded mechanism task queues (Synchronization tasks and asynchronous tasks) events and callback functions Timer event loop (event loop) JavaScript's single-threaded mechanism

One of the language features of JavaScript (and the core of the language) is a single thread . What is a single thread? Simply put, you can only do one thing at a time, and when you have multiple tasks, you can only do it in one order and then execute the next.

The single thread of JavaScript is related to its language use. As a browser scripting language, the main purpose of JavaScript is to complete user interaction and manipulate the DOM. This determines that it can only be single-threaded, otherwise it can cause complex synchronization problems.

Imagine that JavaScript has two threads at the same time, one thread needs to add content to one of the DOM nodes, and the other is to delete the node, so who should be the browser.

So to avoid complexity, JavaScript is a single thread from birth.

To increase CPU utilization, HTML5 proposes a web worker standard that allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not manipulate the DOM. So this standard does not change the nature of JavaScript single-threaded threads. Task Queues

Completing a task one after another means that the task to be completed is to queue, so why do you need to queue up?

There are usually two reasons to queue: The task is computationally large, the CPU is busy; The task needs to be ready so it cannot continue, causing the CPU to idle, waiting for input (I/O devices). > Some tasks you need Ajax to get the data to go down

This JavaScript designer also realizes that it is possible to run the tasks that are already in place to improve the efficiency of the task, that is, to suspend the waiting tasks to the side, and so on to get what needs to be done. It is like answering the phone when the other side left, then there is another call, so you put the current call hangs, and so on the end of the call, and then connect back to the previous call.

So there is the concept of synchronous and asynchronous, and the task is divided into two kinds, one is synchronization task (synchronous), the other is asynchronous task (asynchronous). Synchronization tasks: Tasks that need to be performed are queued on the main thread, one after the other, the previous one completes the next asynchronous task: A task that is not immediately executed but needs to be performed, stored in the task queue, and the task queue notifies the main thread when which asynchronous task can execute. The task then goes into the main thread and is executed. > All synchronous execution can be thought of as asynchronous execution without asynchronous tasks

Specifically, asynchronous execution is as follows: All synchronization tasks are performed on the main thread, forming a broker's storehouses (execution context stack).

That is, all the tasks that can be performed immediately are lined up on the main thread and executed one after another. There is also a task queue, outside the main thread. As long as the asynchronous task has a running result, an event is placed in the task queue.

That is, each asynchronous task is prepared with a unique flag, which is used to identify the corresponding asynchronous task (flag). Once all the synchronization tasks in the execution stack have been completed, the system reads the task queue to see what events are inside. Those corresponding to the asynchronous task, the end of the wait bag, into the execution stack began to be executed.

That is, after the main thread has completed its previous task, it will look at the flag in the task queue to package the corresponding asynchronous tasks to execute. The main thread continues to repeat the above three steps.

As long as the mainline is Cheng, the task queue is read. This process will be repeated, which is the operating mechanism of JavaScript. events and callback functions Events

A "task queue" is a queue of events (also understood as a queue of messages), and the IO device completes a task, adding a time in the task queue to indicate that the relevant asynchronous task can enter the execution stack. The main thread then reads "task queue" to see which events are inside.

Events in the task queue, in addition to events for IO devices, include some user-generated events (such as mouse clicks, page scrolling, and so on). As long as the callback function is specified, these events enter the task queue when they occur, waiting for the main thread to read. callback function

The so-called "callback function" (callback) is the code that will be hung by the main thread. The asynchronous task must specify a callback function, and the corresponding callback function is executed when the main thread begins to perform the asynchronous task.

A "task queue" is a first-in, first-out data structure, preceded by an event that is first read by the main thread. The main thread reading process is basically automatic, as long as the execution stack is emptied, the first event on the task queue automatically enters the main thread. However, if the "timer" is included, the main thread first checks the execution time, and some events only arrive at the specified time to return to the main thread. Event Loop

The main thread reads events from the task queue, and the process is cyclical, so the entire operation is called event loop

To better understand the event Loop, here's a picture from Philip Roberts ' speech.

In the diagram above, the main thread at run time produces heap (heap) and stack (stack), the code in the stack invokes various external APIs and adds various events (Click,load,done) to the task queue. When the code in the stack completes, the main thread reads the task queue and executes the callback functions for those events sequentially.

Executes the code in the stack (the synchronization Task), which is always performed before the task queue (asynchronous task) is read.

var req = new XMLHttpRequest ();
Req.open (' get ', url);
Req.onload = function () {};
Req.onerror = function () {};
Req.send ();

The Req.send method in the above code is that AJAX operations send data to the server, which is an asynchronous task, meaning that only the current script's entire code is executed before the system reads the task queue. Therefore, it is equivalent to the following wording.

var req = new XMLHttpRequest ();
Req.open (' get ', url);
Req.send ();
Req.onload = function () {};
Req.onerror = function () {};

That is, specifying the parts of the callback function (onload and onerror) is irrelevant before or after the Send () method because they are part of the execution stack, and the system always finishes them before it reads the task queue. Timer

In addition to the events that place asynchronous tasks, task queues can place timed events that specify how long some code will be executed. This is called the timer (timer) function, which is the code that executes regularly.

SetTimeout () and setinterval () can be used to register functions that are called one or more times after a specified time, and they operate in exactly the same way, except that the code specified by the former is executed once, and the latter is repeated in the interval of a specified number of milliseconds:

SetInterval (Updateclock, 60000); 60-Second Call once Updateclock ()

Because they are all important global functions in client JavaScript, the method defined as a Window object.

But as a general function, it doesn't actually do anything to the window.

The settimeout () method of the Window object is used to implement a function that runs after the specified number of milliseconds. So it takes two parameters, the first is the callback function, and the second is the number of milliseconds to defer execution. SetTimeout () and SetInterval () return a value that can be passed to Cleartimeout () to cancel the execution of this function.

Console.log (1);
settimeout (function () {Console.log (2);}, 1000);
Console.log (3);

The result of the above code is 1,3,2, because settimeout () delays the second row to 1000 milliseconds after execution.

If the second argument to SetTimeout () is set to 0, the callback function specified (0 millisecond interval) is executed immediately after the current code finishes (execution stack emptying).

settimeout (function () {console.log (1);}, 0);
Console.log (2)

The results of the above code are always 2,1, because the system does not perform the callback function in task queues until the second row is executed.

In short, the meaning of settimeout (fn,o) is to specify that a task executes as early as possible at the earliest available free time of the main thread. It adds an event at the end of the task queue, so until the synchronization task and the task queue existing events are processed, the execution is done.

The HTML5 standard sets the minimum (shortest interval) of the second parameter of settimeout () to be less than 4 milliseconds, and automatically increases if it is below this value.

It is important to note that settimeout () simply inserts the event into the task queue, and the main thread does not execute the callback function it specifies until the current code (the execution stack) has been executed. If the current code takes a long time, it may have to wait long, so there is no way to guarantee that the callback function will be executed at the settimeout () specified.

For historical reasons, the first parameter of settimeout () and setinterval () can be passed in as a string. If you do this, the string is evaluated after the specified timeout or interval (equivalent to executing eval ()).

For an in-depth understanding of how the timer works, it is recommended to read an article by John Resig, author of jquery: http://ejohn.org/blog/how-javascript-timers-work/

I have translated this article myself, if there are any questions, please correct me: http://guoxunique.com/2016/12/07/how-javascript-timers-work/

Refer to Nanyi Teacher's blog http://www.ruanyifeng.com/blog/2014/10/event-loop.html

Reference to the JavaScript Authority guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.