Home  >  Article  >  Web Front-end  >  An introduction to the difference between synchronous and asynchronous in JavaScript

An introduction to the difference between synchronous and asynchronous in JavaScript

不言
不言forward
2019-01-24 09:57:564939browse

This article brings you an introduction to the difference between synchronization and asynchronousness in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The JavaScript language is a "single-threaded" language.
Unlike the Java language, the class inherits Thread and then uses thread.start to open a thread.
So, JavaScript is like an assembly line, just an assembly line, either processing or packaging, and cannot perform multiple tasks and processes at the same time.

"Synchronicity" - immediately reminds people of the word "together";

"Asynchronous", literally speaking, seems to be done in different (different) ways something,
The first word that comes to mind may be "while...while...", such as 'Xiao Ming is eating ice cream and doing homework at the same time'. There is nothing wrong with this at all. After eating the ice cream, he has also finished his homework. asynchronous? That would be a big mistake!

In fact, synchronous and asynchronous,
No matter what, there is only one pipeline (single thread) when doing things ,
Synchronous The difference from asynchronous is that the execution order of each process on this pipeline is different.

The most basic asynchronous functions are the setTimeout and setInterval functions.
They are very common, but few people know that this is actually asynchronous,
because they can control the execution order of js. We can also simply understand it as:
Operations that can change the normal execution sequence of the program can be regarded as asynchronous operations. The following code:

    console.log( "1" );
    setTimeout(function() {
        console.log( "2" )
    }, 0 );
    setTimeout(function() {
        console.log( "3" )
    }, 0 );
    setTimeout(function() {
        console.log( "4" )
    }, 0 );
    console.log( "5" );

What is the output order?

An introduction to the difference between synchronous and asynchronous in JavaScript

It can be seen that although we set the waiting time in setTimeout(function, time) to 0, the function in it is still executed later.

Although the time delay of setTimeout is 0,
the function will also be put into a queue, waiting for the next opportunity to execute,
The current code (referring to the function that does not need to be added to the queue program) must complete before the queue's program completes,
so the results may not be the same as expected.

Here we talk about a "queue" (i.e. task queue).
What is placed in this queue? What is placed is the function in setTimeout.
These functions are in sequence Join the queue,
That is, the programs in all functions in the queue will be executed after all codes outside the queue have been executed.
Why is this? Because when executing a program, the browser will default to methods such as setTimeout and ajax requests as time-consuming programs (although they may not be time-consuming).
Add them to a queue, which is a storage time-consuming process. A queue of programs. After all non-time-consuming programs are executed, the programs in the queue are executed in sequence.

Back to the original starting point-javascript is single-threaded. Single thread means that all tasks need to be queued, and the next task will not be executed until the previous task is completed.
If the previous task takes a long time, the next task will have to wait.

So there is a concept - task queue. If the queue is due to a large amount of calculation and the CPU is too busy, forget it.
But many times the CPU is idle because the IO device (input and output device) is very slow (such as Ajax operations reading data from the network) , but
you have to wait for the result to come out before proceeding. So the designers of the JavaScript language realized that the main thread could completely ignore the IO device at this time,
suspend the waiting tasks, and run the later tasks first. Wait until the IO device returns the result, then go back and continue executing the suspended task.

So, all tasks can be divided into two types,

One is synchronous task (synchronous), the other is asynchronous task (asynchronous). Synchronous tasks refer to tasks that are queued for execution on the main thread.
The next task can only be executed after the previous task has been executed; asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue" (task queue). queue) task,
Only when the main thread task is completed and the "task queue" starts to notify the main thread and request the execution of the task, the task will enter the main thread for execution.

Specifically, the asynchronous running mechanism is as follows:

  1. All synchronous tasks are executed on the main thread, forming an execution context stack.

  2. Besides the main thread, there is also a "task queue". As long as the asynchronous task has running results, an event is placed in the "task queue".

  3. Once all synchronization tasks in the "execution stack" have been executed, the system will read the "task queue" to see what events are in it. Those corresponding asynchronous tasks end the waiting state, enter the execution stack, and start execution.

  4. The main thread keeps repeating the third step above.

As long as the main thread is empty, it will read the "task queue". This is the running mechanism of JavaScript. This process keeps repeating.

The events in the "task queue", in addition to the events of the IO device,
also include some events generated by users (such as mouse clicks, page scrolling, etc.),
such as $ (selectot).click(function), these are relatively time-consuming operations.
As long as the callback functions of these events are specified, these events will enter the "task queue" when they occur, waiting for the main thread to read.

The so-called "callback function" (callback) is the code that will be hung up by the main thread. The function in the click event $(selectot).click(function) mentioned earlier is A callback function. Asynchronous tasks must specify a callback function. When the main thread starts executing an asynchronous task, the corresponding callback function is executed. For example, ajax's success, complete, and error also specify their own callback functions. These functions will be added to the "task queue" and wait for execution.

The above is the detailed content of An introduction to the difference between synchronous and asynchronous in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete